def Deformation(mask_segm_path, par_path, method, pnr, dir_res_i, TRANSFORMIX_PATH): dir_res = dir_res_i+"Transformed_masks/mask_{}_{}".format(method, pnr) if os.path.exists(dir_res_i+"Transformed_masks/") is False: os.mkdir(dir_res_i+"Transformed_masks/") if os.path.exists(dir_res_i+"Transformed_masks/mask_{}_{}".format(method, pnr)) is False: os.mkdir(dir_res_i+"Transformed_masks/mask_{}_{}".format(method, pnr)) path = new_param_file(par_path, "FinalBSplineInterpolationOrder", '3', '0') # Make a new transformix object tr with the CORRECT PATH to transformix tr = elastix.TransformixInterface(parameters=path, transformix_path=TRANSFORMIX_PATH) # Transform the mask with the transformation parameters transformed_image_path = tr.transform_image(mask_segm_path, output_dir=dir_res) transf_mask = sitk.ReadImage(transformed_image_path) transf_mask = sitk.GetArrayFromImage(transf_mask ) # Get the Jacobian matrix (not yet used) jacobian_matrix_path = tr.jacobian_matrix(output_dir=dir_res) # Get the Jacobian determinant (not yet used) jacobian_determinant_path = tr.jacobian_determinant(output_dir=dir_res) # Get the full deformation field (not yet used) deformation_field_path = tr.deformation_field(output_dir=dir_res) return transf_mask, transformed_image_path
def write_transform_images(): image_paths = get_image_paths(fixed_img_name, moving_img_name) results_dir = f"{IMAGES_PATH}/{fixed_img_name}-{moving_img_name}" make_dir(results_dir) print("register", end="", flush=True) el.register(fixed_image=image_paths[0], moving_image=image_paths[1], parameters=param_array, output_dir=results_dir, verbose=False) print(" | transform ", end="", flush=True) nr_params = len(param_array) for i in range(nr_params): print(".", end="", flush=True) temp_dir = f"{results_dir}/{i}" temp_mr_dir = f"{temp_dir}/mr" temp_pros_dir = f"{temp_dir}/pros" make_dir(temp_dir) make_dir(temp_mr_dir) make_dir(temp_pros_dir) transform_path = os.path.join(results_dir, f"TransformParameters.{i}.txt") transform = elastix.TransformixInterface( parameters=transform_path, transformix_path=TRANSFORMIX_PATH) transform_img(image_paths[1], temp_mr_dir, transform) transform_img(image_paths[3], temp_pros_dir, transform) print(" | ", end="", flush=True)
def transform2d(movingnr, slicenr, runnr, transformmask=True): movingnr = str(movingnr) + '_' + str(slicenr) transform_path = os.path.join(f'results{runnr}', r'TransformParameters.0.txt') moving_image_path = os.path.join(data_path, f"p{movingnr}\mr_bffe.mhd") output_path = f'results{runnr}' #make a new transformix object tr tr = elastix.TransformixInterface(parameters=transform_path, transformix_path=transformix_path) #transform a new image with the transformation parameters tr.transform_image(moving_image_path, output_dir=output_path) #get the Jacobian matrix tr.jacobian_matrix(output_dir=output_path) #get the Jacobian determinant tr.jacobian_determinant(output_dir=output_path) # Get the full deformation field tr.deformation_field(output_dir=output_path) if transformmask: moving_image_path = os.path.join(data_path, f"p{movingnr}\prostaat.mhd") #Change BSplineInterpolationOrder in parameterfile for mask transform interporder = readparameter(transform_path, "FinalBSplineInterpolationOrder") replace(transform_path, "FinalBSplineInterpolationOrder", 0) #make a new transformix object tr tr = elastix.TransformixInterface(parameters=transform_path, transformix_path=transformix_path) output_path += r'\transformedmask' if os.path.exists(output_path) is False: os.mkdir(output_path) #transform a new image with the transformation parameter tr.transform_image(moving_image_path, output_dir=output_path) #Change back BSplineInterpolationOrder in parameterfile replace(transform_path, "FinalBSplineInterpolationOrder", interporder)
def get_transform(fixed_img_path, moving_img_path): el.register(fixed_image=fixed_img_path, moving_image=moving_img_path, parameters=param_array, output_dir=TEMP_RESULTS_PATH, verbose=False) transform_path = os.path.join( TEMP_RESULTS_PATH, f"TransformParameters.{len(param_array) - 1}.txt") return elastix.TransformixInterface(parameters=transform_path, transformix_path=TRANSFORMIX_PATH)
def registration(parameters, fix_im_p, mov_im_p, mov_im_m_p, name): ELASTIX_PATH = os.path.join( r'C:\Users\s148534\PycharmProjects\myfolder\elastix.exe') TRANSFORMIX_PATH = os.path.join( r'C:\Users\s148534\PycharmProjects\myfolder\transformix.exe') if not os.path.exists(ELASTIX_PATH): raise IOError( 'Elastix cannot be found, please set the correct ELASTIX_PATH.') if not os.path.exists(TRANSFORMIX_PATH): raise IOError( 'Transformix cannot be found, please set the correct TRANSFORMIX_PATH.' ) # Define a new elastix object 'el' with the correct path to elastix el = elastix.ElastixInterface(elastix_path=ELASTIX_PATH) # Make a results directory if none exists if not os.path.exists('results' + name): os.mkdir('results' + name) # # Execute the registration. Make sure the paths below are correct, and # that the results folder exists from where you are running this script parm = parameters el.register(fixed_image=fix_im_p, moving_image=mov_im_p, parameters=[os.path.join(parm)], output_dir='results' + name) # Find the results transform_path = os.path.join('results' + name, 'TransformParameters.0.txt') tr_im_p = os.path.join('results' + name, 'result.0.mhd') # Make a new transformix object tr with the CORRECT PATH to transformix tr = elastix.TransformixInterface(parameters=transform_path, transformix_path=TRANSFORMIX_PATH) # Make a results directory if none exists if not os.path.exists('results_tr' + name): os.mkdir('results_tr' + name) tr_im_m_p = tr.transform_image(mov_im_m_p, output_dir=r'results_tr' + name) return tr_im_p, tr_im_m_p
def register_get_transform(input_fixed_img_path, input_moving_img_path, input_param_array): # Execute the registration. print("registration", end=" ", flush=True) begin_time = time.time() el.register(fixed_image=input_fixed_img_path, moving_image=input_moving_img_path, parameters=input_param_array, output_dir=results_dir) global duration duration = time.gmtime(time.time() - begin_time) # Make a new transformix object print("transformation", end=" ", flush=True) transform_path = os.path.join( results_dir, f"TransformParameters.{len(input_param_array) - 1}.txt") return_transform = elastix.TransformixInterface( parameters=transform_path, transformix_path=TRANSFORMIX_PATH) return return_transform
def Transform_GT(data_path, results_path, transformix_path): """Takes as input a file path to: 1. Folder where data is stored 2. Folder where results are stored 3. Path to transformix.exe file This function applies the registration found for moving -> fixed image to the masks (groundtruth, GT) of the moving image, then writes this as .mhd & .raw files to the same folder as where the registration result & parameter file was written. """ mri, masks_paths = Import_Files_string(data_path) # Store all path names in a dictionary according to their patient ID for easy referencing # via slicing out path names masks_dict = {} for path in masks_paths: masks_dict[path[-17:-13]] = path # Collect a list of all transform parameter files files = glob.glob(results_path + r'\p*\p*\TransformParameters.0.txt') # Setting "FinalBSplineInterpolationOrder" to 0 prevents circular pixelated edges of transferred masks(doesnt draw a thrid order polynomial.) for current in files: with fileinput.FileInput(current, inplace=True) as file: for line in file: print(line.replace("(FinalBSplineInterpolationOrder 3)", "(FinalBSplineInterpolationOrder 0)"), end='') # Apply transformation of parameterfile i to its respective mask, then write to file nFiles = len(files) for n, parameterfile in zip(range(nFiles), files): # Print progress print('{} registrations out of {} performed'.format(n, nFiles)) current_path = parameterfile[:-25] T = elastix.TransformixInterface(parameters=parameterfile, transformix_path=transformix_path) path_to_transformed_image = T.transform_image( image_path=masks_dict[parameterfile[-30:-26]], output_dir=current_path)
moving_image=mr_image_path, parameters=[os.path.join('parameterfiles', 'parameters_affine.txt'), os.path.join('parameterfiles', 'parameters_bspline.txt')], output_dir=result_path) final_result_path = os.path.join(result_path, 'result.1.mhd') transform_path = os.path.join(result_path, 'TransformParameters.1.txt') transform_path0 = os.path.join(result_path, 'TransformParameters.0.txt') transform_path1 = os.path.join(result_path, 'TransformParameters.1.txt') final_transform_path = os.path.join(result_path, 'transform_pathfinal.txt') # Change FinalBSplineInterpolationOrder to 0 for binary mask transformation TransformParameterFileEditor(transform_path1, transform_path0, final_transform_path).modify_transform_parameter_file() # Make a new transformix object tr with the CORRECT PATH to transformix tr = elastix.TransformixInterface(parameters=final_transform_path, transformix_path=TRANSFORMIX_PATH) transformed_pr_path = tr.transform_image(pr_image_path, output_dir=result_path) image_array_tpr = sitk.GetArrayFromImage(sitk.ReadImage(transformed_pr_path)) log_path = os.path.join(result_path, 'IterationInfo.1.R3.txt') log = elastix.logfile(log_path) DSC.append(dice_coef(image_array_opr, image_array_tpr)) SNS.append(sensitivity(image_array_opr, image_array_tpr)) SPC.append(specificity(image_array_opr, image_array_tpr)) finalMI.append(statistics.mean(log['metric'][-50:-1])) fig, (ax1,ax2,ax3) = plt.subplots(1, 3, figsize=(15, 5)) ax1.scatter(finalMI,DSC) ax1.set_title("DSC")
def register_patients(fixed_subject, moving_subject, result_dir_start): image_folder = "TrainingData" param_file = 'Training/3Dtrans.txt' param_file_spline = 'Training/3Dspline.txt' result_dir = os.path.join(result_dir_start, "trans") fixed_subject_path = os.path.join(image_folder, fixed_subject) moving_subject_path = os.path.join(image_folder, moving_subject) fixed_img_path = os.path.join(fixed_subject_path, 'mr_bffe.mhd') fixed_seg_img_path = os.path.join(fixed_subject_path, 'prostaat.mhd') moving_img_path = os.path.join(moving_subject_path, 'mr_bffe.mhd') moving_seg_img_path = os.path.join(moving_subject_path, 'prostaat.mhd') fixed_img = sitk.GetArrayFromImage(sitk.ReadImage(fixed_img_path)) fixed_seg_img = sitk.GetArrayFromImage(sitk.ReadImage(fixed_seg_img_path)) moving_img = sitk.GetArrayFromImage(sitk.ReadImage(moving_img_path)) moving_seg_img = sitk.GetArrayFromImage( sitk.ReadImage(moving_seg_img_path)) # Define a new elastix object 'el' with the correct path to elastix el = elastix.ElastixInterface(elastix_path=ELASTIX_PATH) # Make a results directory if none exists if not os.path.exists(result_dir): os.mkdir(result_dir) elif len(os.listdir(result_dir)) != 0: inp = input("OK to overwrite? (y/n) ") if inp != 'y': sys.exit() # Execute the registration. Make sure the paths below are correct, and # that the results folder exists from where you are running this script ##pre-translation of the moving image el.register(fixed_image=fixed_img_path, moving_image=moving_img_path, parameters=[param_file], output_dir=result_dir) # Find the results transform_path = os.path.join(result_dir, 'TransformParameters.0.txt') #result_path = os.path.join(result_dir, 'result.0.mhd') ''' # Open the logfile into the dictionary log for i in range(5): log_path = os.path.join(result_dir, 'IterationInfo.0.R{}.txt'.format(i)) log = elastix.logfile(log_path) # Plot the 'metric' against the iteration number 'itnr' plt.plot(log['itnr'], log['metric']) plt.legend(['Resolution {}'.format(i) for i in range(5)]) ''' #transformed_moving_image = sitk.GetArrayFromImage(sitk.ReadImage(os.path.join(result_dir,'result.0.mhd'))) # Make a new transformix object tr with the CORRECT PATH to transformix tr = elastix.TransformixInterface(parameters=transform_path, transformix_path=TRANSFORMIX_PATH) # Transform a new image with the transformation parameters img_out = os.path.join(result_dir, 'image') if not os.path.exists(img_out): os.mkdir(img_out) seg_out = os.path.join(result_dir, 'segmentation') if not os.path.exists(seg_out): os.mkdir(seg_out) t_img_path = tr.transform_image(moving_img_path, output_dir=img_out) t_seg_path = tr.transform_image(moving_seg_img_path, output_dir=seg_out) #t_img = sitk.GetArrayFromImage(sitk.ReadImage(t_img_path)) #t_seg_img = sitk.GetArrayFromImage(sitk.ReadImage(t_seg_path)) ##B spline registration result_dir = os.path.join(result_dir_start, 'Bspline') if not os.path.exists(result_dir): os.mkdir(result_dir) el.register(fixed_image=fixed_img_path, moving_image=t_img_path, parameters=[param_file_spline], output_dir=result_dir) transform_path2 = os.path.join(result_dir, 'TransformParameters.0.txt') #result_path2 = os.path.join(result_dir, 'result.0.mhd') tr = elastix.TransformixInterface(parameters=transform_path2, transformix_path=TRANSFORMIX_PATH) # Transform a new image with the transformation parameters img_out = os.path.join(result_dir, 'image') if not os.path.exists(img_out): os.mkdir(img_out) seg_out = os.path.join(result_dir, 'segmentation') if not os.path.exists(seg_out): os.mkdir(seg_out) t_img_path2 = tr.transform_image(t_img_path, output_dir=img_out) t_seg_path2 = tr.transform_image(t_seg_path, output_dir=seg_out) t_img2 = sitk.GetArrayFromImage(sitk.ReadImage(t_img_path2)) t_seg_img2 = sitk.GetArrayFromImage(sitk.ReadImage(t_seg_path2)) dice = dice_overlap(t_seg_img2, fixed_seg_img) print('Dice similarity score with ground truth is {}'.format(dice)) #visualization of the results visualize_patient(fixed_img, fixed_seg_img, moving_img, moving_seg_img, t_img2, t_seg_img2) ''' for i in range(np.shape(t_seg_img2)[0]): fig, ax = plt.subplots(1, 3, figsize=(10, 15)) ax[0].imshow(moving_seg_img[i,:,:], cmap='gray') ax[0].set_title('Ground Truth') ax[1].imshow(t_seg_img2[i,:,:], cmap='gray') ax[1].set_title('Estimation') ax[2].imshow(fixed_seg_img[i,:,:], cmap='gray') ax[2].set_title('Fixed Atlas') plt.show() #make video of images out = cv2.VideoWriter('project.avi',cv2.VideoWriter_fourcc('M','J','P','G'), float(10), (np.shape(t_img2)[2],np.shape(t_img2)[1]), isColor=True) for i in range(np.shape(t_seg_img2)[0]): out.write(t_seg_img2[i,:,:]) out.release() ''' # ## Get the Jacobian matrix #jacobian_matrix_path = tr.jacobian_matrix(output_dir=result_dir) # ## Get the Jacobian determinant #jacobian_determinant_path = tr.jacobian_determinant(output_dir=result_dir) # ## Get the full deformation field #deformation_field_path = tr.deformation_field(output_dir=result_dir) # #jacobian_image = imageio.imread(jacobian_determinant_path.replace('dcm', 'tiff')) #jacobian_binary = jacobian_image>0 # ## Add a plot of the Jacobian determinant (in this case, the file is a tiff file) #ax[3].imshow(jacobian_binary,cmap='gray') #ax[3].set_title('Jacobian\ndeterminant') return t_seg_img2, dice
image_array_s = sitk.GetArrayFromImage(itk_image) f_image = sitk.ReadImage(fixed_image_path)[:,:,20] fixed_image_s = sitk.GetArrayFromImage(f_image) m_image = sitk.ReadImage(moving_image_path)[:,:,20] moving_image_s = sitk.GetArrayFromImage(m_image) f, (ax0, ax1, ax2,ax3) = plt.subplots(1, 4) ax0.imshow(fixed_image_s, cmap='gray') ax0.set_title('fixed') ax1.imshow(moving_image_s, cmap='gray') ax1.set_title('moving') ax2.imshow(image_array_s, cmap='gray') ax2.set_title('registered image') # Make a new transformix object tr with the CORRECT PATH to transformix tr = elastix.TransformixInterface(parameters=os.path.join(dir_res, 'TransformParameters.0.txt'), transformix_path=TRANSFORMIX_PATH) # Transform a new image with the transformation parameters transformed_image_path = tr.transform_image(moving_image_path, output_dir=dir_res) # Get the Jacobian matrix jacobian_matrix_path = tr.jacobian_matrix(output_dir=dir_res) # Get the Jacobian determinant jacobian_determinant_path = tr.jacobian_determinant(output_dir=dir_res) # Get the full deformation field deformation_field_path = tr.deformation_field(output_dir=dir_res) ax3.imshow(imageio.imread(jacobian_determinant_path.replace('dcm', 'tiff'))[40])