본문 바로가기
반치용/기타 및 저장

[저장]파이썬을 이용한 dicom(dcm) 비식별화

by  반  2021. 3. 23.

설명은 코드로 대체합니다.

import os
import pydicom

# 파일리스트 추출 가장 짧은 코드 (현재폴더안의 파일/폴더명 추출)

# 파일은 image 폴더 내에 넣어야 됨
rootdir = './image/'
# 해당 폴더 내에 파일/폴더 리스팅
files = os.listdir(rootdir)


# 처리 함수
def Fn_di_di(temp_img):
    
    # 메타 비식별화 (변경할 내용들 참고)
    temp_img.SeriesDate='Anonimized'
    temp_img.StudyDate='Anonimized'
    temp_img.ContentDate ='Anonimized'    
    temp_img.AccessionNumber='Anonimized'    
    temp_img.PatientName='Anonimized'
    temp_img.PatientID='Anonimized'
    temp_img.PatientBirthDate='Anonimized'
    
    # 픽셀 array 상태로 핸들링
    temp_img.pixel_array[0:20] = 0 #위 삭제
    temp_img.pixel_array[460:480] = 0 #아래 삭제
    temp_img.pixel_array[0:480,:100] = 0 #왼쪽 삭제
    temp_img.pixel_array[0:480,610:640] = 0 #오른쪽 삭제
    
    # bytes로 전환하여 저장
    temp_img.PixelData = temp_img.pixel_array.tobytes()
     
    #작업중 이미지 확인용    
    #plt.imshow(temp_img.pixel_array, cmap=plt.cm.bone)
        
    return temp_img
    
    

# 파일 결과물 확인용
target_files = []

# 개별 파일에 대해 작동
for i in files:
    if i[-3:] == 'dcm': # dcm 파일에만 작동
        
        #결과 확인용. 작동에 불필요
        target_files.append(rootdir + 'edited_' + i)
        
        # 파일 불러오기
        filename = rootdir + i        
        dataset = pydicom.dcmread(filename)
        
        # 파일 저장용 파일명
        edited_filename = rootdir + 'edited_' + i
        
        # 처리 (Fn_di_di)
        temp_img = Fn_di_di(dataset)
        
        # 저장
        temp_img.save_as(edited_filename)#,write_like_original=False)
        
################### 끝 ####################

# 결과물 확인용 코드

# 시각화용. 작동시 불필요
import matplotlib.pyplot as plt

temp_file = target_files[1]
test_data = pydicom.dcmread(temp_file)
print('file name : ' , temp_file)
print()
#test_data = pydicom.dcmread('./image/edited_11990007.dcm')
plt.imshow(test_data.pixel_array, cmap=plt.cm.bone)
print(test_data)

댓글