7 def mri_to_png(mri_file, png_file):
8 """ Function to convert from a DICOM image to png
10 @param mri_file: An opened file like object to read te dicom data
11 @param png_file: An opened file like object to write the png data
14 # Extracting data from the mri file
15 plan = dicom.read_file(mri_file)
16 shape = plan.pixel_array.shape
20 for row in plan.pixel_array:
24 if col > max_val: max_val = col
25 image_2d.append(pixels)
27 # Rescaling grey scale between 0-255
32 col_scaled = int((float(col) / float(max_val)) * 255.0)
33 row_scaled.append(col_scaled)
34 image_2d_scaled.append(row_scaled)
36 # Writing the PNG file
37 w = png.Writer(shape[0], shape[1], greyscale=True)
38 w.write(png_file, image_2d_scaled)
41 def convert_file(mri_file_path, png_file_path):
42 """ Function to convert an MRI binary file to a
45 @param mri_file_path: Full path to the mri file
46 @param png_file_path: Fill path to the png file
49 # Making sure that the mri file exists
50 if not os.path.exists(mri_file_path):
51 raise Exception('File "%s" does not exists' % mri_file_path)
53 # Making sure the png file does not exist
54 if os.path.exists(png_file_path):
55 raise Exception('File "%s" already exists' % png_file_path)
57 mri_file = open(mri_file_path, 'rb')
58 png_file = open(png_file_path, 'wb')
60 mri_to_png(mri_file, png_file)
65 def convert_folder(mri_folder, png_folder):
66 """ Convert all MRI files in a folder to png files
67 in a destination folder
70 # Create the folder for the pnd directory structure
71 os.makedirs(png_folder)
73 # Recursively traverse all sub-folders in the path
74 for mri_sub_folder, subdirs, files in os.walk(mri_folder):
75 for mri_file in os.listdir(mri_sub_folder):
76 mri_file_path = os.path.join(mri_sub_folder, mri_file)
78 # Make sure path is an actual file
79 if os.path.isfile(mri_file_path):
81 # Replicate the original file structure
82 rel_path = os.path.relpath(mri_sub_folder, mri_folder)
83 png_folder_path = os.path.join(png_folder, rel_path)
84 if not os.path.exists(png_folder_path):
85 os.makedirs(png_folder_path)
86 png_file_path = os.path.join(png_folder_path, '%s.png' % mri_file)
89 # Convert the actual file
90 convert_file(mri_file_path, png_file_path)
91 print('SUCCESS>', mri_file_path, '-->', png_file_path)
92 except Exception as e:
93 print('FAIL>', mri_file_path, '-->', png_file_path, ':', e)
96 if __name__ == '__main__':
97 parser = argparse.ArgumentParser(description="Convert a dicom MRI file to png")
98 parser.add_argument('-f', action='store_true')
99 parser.add_argument('dicom_path', help='Full path to the mri file')
100 parser.add_argument('png_path', help='Full path to the generated png file')
102 args = parser.parse_args()
105 convert_folder(args.dicom_path, args.png_path)
107 convert_file(args.dicom_path, args.png_path)