deffindAllFile(base): for root, ds, fs in os.walk(base): for f in ds: fullname = os.path.join(root, f) yield fullname defcovert(inputpath,savepath): import pydicom as dicom import matplotlib.pyplot as plt import os import cv2 import PIL # optional import pandas as pd import csv # make it True if you want in PNG format PNG = False # Specify the .dcm folder path folder_path =inputpath # Specify the .jpg/.png folder path jpg_folder_path =savepath images_path = os.listdir(folder_path) # list of attributes available in dicom image # download this file from the given link # https://github.com/vivek8981/DICOM-to-JPG dicom_image_description = pd.read_csv("/add_you_path/dicom_image_description.csv")
withopen(jpg_folder_path+'/Patient_Detail.csv', 'w', newline ='') as csvfile: fieldnames = list(dicom_image_description["Description"]) writer = csv.writer(csvfile, delimiter=',') writer.writerow(fieldnames) for n, image inenumerate(images_path): ds = dicom.dcmread(os.path.join(folder_path, image)) rows = [] pixel_array_numpy = ds.pixel_array if PNG == False: image = image.replace('.dcm', '.jpg') else: image = image.replace('.dcm', '.png') cv2.imwrite(os.path.join(jpg_folder_path, image), pixel_array_numpy) if n % 50 == 0: print('{} image converted'.format(n)) for field in fieldnames: try: ds.data_element(field) except KeyError: rows.append('') continue else: if ds.data_element(field) isNone: rows.append('') else: x = str(ds.data_element(field)).replace("'", "") y = x.find(":") x = x[y+2:] rows.append(x) writer.writerow(rows)
import os ##get all need dir(absoulte path) base = 'you dataset path' all_dir = [] for i in findAllFile(base): ##if i.count('/') ==10: all_dir.append(i) ##dir add Covert for i inrange(len(all_dir)): temp = all_dir[i].split("/", 10) temp[7] = 'ICDC-Glioma_Covert' all_dir[i] = '/'.join(temp) ## dir sort ##method 1 all_dir = sorted(all_dir,key = lambda i:len(i),reverse=False) ##method 2 ##all_dir.sort(key = lambda i:len(i),reverse=True) ## create content tree for i in all_dir: os.makedirs(i) ##find leaf node ,covert dcm to jpg ##get all need dir(absoulte path) leaf = [] for i in findAllFile(base): if i.count('/') ==10: leaf.append(i) for father_path in leaf: os.chdir(father_path) retval = os.getcwd() print("当前工作目录为 %s" % retval) temp = father_path.split("/", 10) temp[7] = 'ICDC-Glioma_Covert' save_path = '/'.join(temp) ##begin covert covert(father_path,save_path) print("done")