資源簡介
醫學圖像普遍的dicom格式,但深度學習需要jpg或者png格式,所以需要批量的將dicom轉換格式

代碼片段和文件信息
import?os
import?SimpleITK?as?sitk
import?numpy?as?np
import?cv2
def?endWith(*endstring):
????ends=endstring
????def?run(s):
????????f=map(s.endswithends)
????????if?True?in?f:
????????????return?s
????return?run
def?convert_from_dicom_to_jpg(img?low_window?high_window?save_path):
????lungwin?=?np.array([low_window?*?1.?high_window?*?1.])
????newimg?=?(img?-?lungwin[0])?/?(lungwin[1]?-?lungwin[0])??#?歸一化
????newimg?=?(newimg?*?255).astype(‘uint8‘)??#?將像素值擴展到[0255]
????cv2.imwrite(save_path?newimg?[int(cv2.IMWRITE_JPEG_QUALITY)?100])
if?__name__==‘__main__‘:
????list_file=os.listdir(‘C:/Data/001/C+?delay‘)
????a=endWith(‘.dcm‘)
????f_file=filter(alist_file)
????#data=[]
????for?i?in?f_file:
????????#print(i)??#dcm的文件名
????????#data.append(i)
????#?#print(len(data))
????#?print(data)
????#?data.reverse()
????#?print(data)
????????#?下面是將對應的dicom格式的圖片轉成jpg
????????dcm_image_path?=?‘C:/Data/001/C+?delay/{}‘.format(i)??#?讀取dicom文件
????????output_jpg_path?=?‘C:/Data/001/C+?delay/{}.jpg‘.format(i)
????????ds_array?=?sitk.ReadImage(dcm_image_path)??#?讀取dicom文件的相關信息
????????img_array?=?sitk.GetArrayFromImage(ds_array)??#?獲取array
????????#?SimpleITK讀取的圖像數據的坐標順序為zyx,即從多少張切片到單張切片的寬和高,此處我們讀取單張,因此img_array的shape
????????#?類似于?(1,height,width)的形式
????????shape?=?img_array.shape
????????print(shape)
????????img_array?=?np.reshape(img_array?(shape[1]?shape[2]))??#?獲取array中的height和width
????????high?=?np.max(img_array)
????????low?=?np.min(img_array)
????????convert_from_dicom_to_jpg(img_array?low?high?output_jpg_path)??#?調用函數,轉換成jpg文件并保存到對應的路徑
????????print(‘正在轉換第{}張‘.format(i))
?屬性????????????大小?????日期????時間???名稱
-----------?---------??----------?-----??----
?????目錄???????????0??2018-12-01?10:30??將.dcm導出成.jpg\
?????文件????????1917??2018-12-01?00:43??將.dcm導出成.jpg\file_read.py
評論
共有 條評論