def try_gadgetrontonifti(nifti_filename, mr_recon_h5_filename): time.sleep(0.5) sys.stderr.write('\n# --------------------------------------------------------------------------------- #\n') sys.stderr.write('# Starting Gadgetron to Nifti test...\n') sys.stderr.write('# --------------------------------------------------------------------------------- #\n') time.sleep(0.5) # Read ISMRMRD image ismrmrd_im = mr.ImageData(mr_recon_h5_filename) # Convert ISMRMRD image to nifti nifti_from_ismrmrd = reg.ImageData(ismrmrd_im) # Read vendor-reconstructed image dicom_im = reg.ImageData(nifti_filename) # Standardise to remove scaling problems dicom_im.standardise() nifti_from_ismrmrd.standardise() # Compare the two. Since the images are being reconstructed independently, there is no # guarantee they will perfectly match. So we need an data-dependent acceptance threshold. if not reg.ImageData.are_equal_to_given_accuracy(dicom_im, nifti_from_ismrmrd, 165.): raise AssertionError("Conversion from ISMRMRD to Nifti failed") time.sleep(0.5) sys.stderr.write('\n# --------------------------------------------------------------------------------- #\n') sys.stderr.write('# Finished Gadgetron to Nifti test.\n') sys.stderr.write('# --------------------------------------------------------------------------------- #\n') time.sleep(0.5)
def objective_function(optimise_array, static_image, dynamic_path, dvf_path, weighted_normalise, dynamic_data_magnitude): static_image.fill( np.reshape(optimise_array, static_image.as_array().astype(np.double).shape)) objective_value = 0.0 for i in range(len(dynamic_path)): dynamic_image = reg.NiftiImageData(dynamic_path[i]) dvf_image = reg.NiftiImageData3DDeformation(dvf_path[i]) resampler = reg.NiftyResample() resampler.set_reference_image(static_image) resampler.set_floating_image(dynamic_image) resampler.add_transformation(dvf_image) resampler.set_interpolation_type_to_cubic_spline() objective_value = objective_value + (np.nansum( np.square(dynamic_image.as_array().astype(np.double) - ((np.nansum(dynamic_image.as_array().astype(np.double), dtype=np.double) / dynamic_data_magnitude) * warp_image_forward(resampler, static_image)), dtype=np.double), dtype=np.double) * weighted_normalise[i]) print("Objective function value: {0}".format(str(objective_value))) return objective_value
def get_resamplers(static_image, dynamic_array, dvf_array, output_path): resamplers = [] static_image_path = "{0}/temp_static.nii".format(output_path) dynamic_array_path = "{0}/temp_dynamic.nii".format(output_path) dvf_array_path = "{0}/temp_dvf.nii".format(output_path) for j in range(len(dynamic_array)): resampler = reg.NiftyResample() static_image.write(static_image_path) dynamic_array[j].write(dynamic_array_path) dvf_array[j].write(dvf_array_path) temp_static = reg.NiftiImageData(static_image_path) temp_dynamic = reg.NiftiImageData(dynamic_array_path) temp_dvf = reg.NiftiImageData3DDeformation(dvf_array_path) resampler.set_reference_image(temp_static) resampler.set_floating_image(temp_dynamic) resampler.add_transformation(temp_dvf) resampler.set_interpolation_type_to_linear() resamplers.append(resampler) return resamplers
def try_stirtonifti(nifti_filename): time.sleep(0.5) sys.stderr.write('\n# --------------------------------------------------------------------------------- #\n') sys.stderr.write('# Starting STIR to Nifti test...\n') sys.stderr.write('# --------------------------------------------------------------------------------- #\n') time.sleep(0.5) # Load the image as a NiftiImageData3D image_nifti = reg.NiftiImageData3D(nifti_filename) # Read as STIRImageData, convert to NiftiImageData3D and save to file image_stir = pet.ImageData(nifti_filename) image_nifti_from_stir = reg.NiftiImageData3D(image_stir) image_nifti_from_stir.write('results/stir_to_nifti.nii',image_nifti.get_original_datatype()) # Compare the two if image_nifti != image_nifti_from_stir: raise AssertionError("Conversion from STIR to Nifti failed.") # Resample and then check that voxel values match resample = reg.NiftyResample() resample.set_floating_image(image_stir) resample.set_reference_image(image_nifti) resample.set_interpolation_type_to_nearest_neighbour() resample.process() # as_array() of both original images should match if not numpy.array_equal(image_nifti.as_array(),resample.get_output().as_array()): raise AssertionError("as_array() of sirf.Reg.NiftiImageData and resampled sirf.STIR.ImageData are different.") time.sleep(0.5) sys.stderr.write('\n# --------------------------------------------------------------------------------- #\n') sys.stderr.write('# Finished STIR to Nifti test.\n') sys.stderr.write('# --------------------------------------------------------------------------------- #\n') time.sleep(0.5)
def op_test(static_image, output_path): static_image_path = "{0}/temp_static.nii".format(output_path) static_image.write(static_image_path) temp_static = reg.NiftiImageData(static_image_path) temp_at = reg.AffineTransformation() temp_at_array = temp_at.as_array() temp_at_array[0][0] = 1.25 temp_at_array[1][1] = 1.25 temp_at_array[2][2] = 1.25 temp_at_array[3][3] = 1.25 temp_at = reg.AffineTransformation(temp_at_array) resampler = reg.NiftyResample() resampler.set_reference_image(temp_static) resampler.set_floating_image(temp_static) resampler.add_transformation(temp_at) resampler.set_interpolation_type_to_linear() warp = warp_image_forward(resampler, temp_static) warped_image = static_image.clone() warped_image.fill(warp) warped_image.write("{0}/op_test_warp_forward.nii".format(output_path)) difference = temp_static.as_array().astype(np.double) - warp difference_image = temp_static.clone() difference_image.fill(difference) difference_image.write( "{0}/op_test_warp_forward_difference.nii".format(output_path)) warp = warp_image_adjoint(resampler, temp_static) warped_image = temp_static.clone() warped_image.fill(warp) warped_image.write("{0}/op_test_warp_adjoint.nii".format(output_path)) difference = temp_static.as_array().astype(np.double) - warp difference_image = temp_static.clone() difference_image.fill(difference) difference_image.write( "{0}/warp_adjoint_difference.nii".format(output_path)) return True
def setUp(self): image1 = reg.ImageData(os.path.join( examples_data_path('Registration'),'test2.nii.gz') ) image2 = reg.ImageData(os.path.join( examples_data_path('Registration'),'test2.nii.gz') ) self.image1 = image1 self.image2 = image2
def output_input(static_image, dynamic_path, dvf_path, output_path): static_image.write("{0}/static_image.nii".format(output_path)) for i in range(len(dynamic_path)): dynamic_image = reg.NiftiImageData(dynamic_path[i]) dvf_image = reg.NiftiImageData3DDeformation(dvf_path[i]) dynamic_image.write("{0}/dynamic_image_{1}.nii".format( output_path, str(i))) dvf_image.write("{0}/dvf_image_{1}.nii".format(output_path, str(i))) return True
def test_for_adj(static_image, dvf_array, output_path): static_image_path = "{0}/temp_static.nii".format(output_path) dvf_array_path = "{0}/temp_dvf.nii".format(output_path) for i in range(len(dvf_array)): static_image.write(static_image_path) dvf_array[i].write(dvf_array_path) temp_static = reg.NiftiImageData(static_image_path) temp_dvf = reg.NiftiImageData3DDeformation(dvf_array_path) resampler = reg.NiftyResample() resampler.set_reference_image(temp_static) resampler.set_floating_image(temp_static) resampler.add_transformation(temp_dvf) resampler.set_interpolation_type_to_linear() warp = warp_image_forward(resampler, temp_static) warped_image = static_image.clone() warped_image.fill(warp) warped_image.write("{0}/warp_forward_{1}.nii".format( output_path, str(i))) difference = temp_static.as_array().astype(np.double) - warp difference_image = temp_static.clone() difference_image.fill(difference) difference_image.write("{0}/warp_forward_difference_{1}.nii".format( output_path, str(i))) warp = warp_image_adjoint(resampler, temp_static) warped_image = temp_static.clone() warped_image.fill(warp) warped_image.write("{0}/warp_adjoint_{1}.nii".format( output_path, str(i))) difference = temp_static.as_array().astype(np.double) - warp difference_image = temp_static.clone() difference_image.fill(difference) difference_image.write("{0}/warp_adjoint_difference_{1}.nii".format( output_path, str(i))) return True
def reg_nac(ref, flo_path, list_NACs): i = 0 nac_reg = Reg.NiftyAladinSym() nac_reg.set_reference_image(ref) for image in sorted_alphanumeric(list_NACs): nac_file = flo_path + image print(nac_file) flo = Eng_flo.ImageData(nac_file) nac_reg.set_floating_image(flo) nac_reg.process() tm_nac = nac_reg.get_transformation_matrix_forward() tm_nac.write(path_moco + 'tm_nac_' + str(i)) i += 1
def reg_epi(ref, flo_path): i = 0 resampler2 = Reg.NiftyAladinSym() resampler2.set_reference_image(ref) for image in sorted_alphanumeric(os.listdir(flo_path)): flo_file = flo_path + image print(flo_file) flo = Eng_flo.ImageData(flo_file) resampler2.set_floating_image(flo) resampler2.process() tm_epi = resampler2.get_transformation_matrix_forward() tm_epi.write(path_EPI + 'tm_epi_' + str(i)) i += 1
def transform_image(fixed_im_name, moving_im_name, reg_resample): """ Randomly transform 2D image by translation or rotation. fixed_im_name = """ trans_file = 'temp_trans_file.txt' angle = random.uniform(-1, 1) tr_x = random.uniform(-1, 1) tr_y = random.uniform(-1, 1) theta = angle * (math.pi / 2) transform = Reg.AffineTransformation( np.array([[math.cos(theta), -math.sin(theta), 0, tr_x * 25], [math.sin(theta), math.cos(theta), 0, tr_y * 25], [0, 0, 1, 0], [0, 0, 0, 1]])) transform.write(trans_file) args = [ reg_resample, "-ref", fixed_im_name + ".nii", "-flo", fixed_im_name + ".nii", "-res", moving_im_name + ".nii", "-trans", trans_file ] popen = subprocess.Popen(args, stdout=subprocess.PIPE) popen.wait() os.remove(trans_file) return [tr_x, tr_y, angle]
def gradient_function(optimise_array, static_image, dynamic_path, dvf_path, weighted_normalise, dynamic_data_magnitude): static_image.fill( np.reshape(optimise_array, static_image.as_array().astype(np.double).shape)) gradient_value = static_image.clone() gradient_value.fill(0.0) adjoint_image = static_image.clone() for i in range(len(dynamic_path)): dynamic_image = reg.NiftiImageData(dynamic_path[i]) dvf_image = reg.NiftiImageData3DDeformation(dvf_path[i]) resampler = reg.NiftyResample() resampler.set_reference_image(static_image) resampler.set_floating_image(dynamic_image) resampler.add_transformation(dvf_image) resampler.set_interpolation_type_to_cubic_spline() adjoint_image.fill(( (np.nansum(dynamic_image.as_array().astype(np.double), dtype=np.double) / dynamic_data_magnitude) * warp_image_forward(resampler, static_image)) - dynamic_image.as_array().astype(np.double)) gradient_value.fill((gradient_value.as_array().astype(np.double) + (warp_image_adjoint(resampler, adjoint_image) * weighted_normalise[i]))) # gradient_value.write("{0}/gradient.nii".format(output_path)) print( "Max gradient value: {0}, Mean gradient value: {1}, Gradient norm: {2}" .format( str(np.amax(gradient_value.as_array().astype(np.double))), str( np.nanmean( np.abs(gradient_value.as_array().astype(np.double), dtype=np.double))), str(np.linalg.norm(gradient_value.as_array().astype(np.double))))) return np.ravel(gradient_value.as_array().astype(np.double)).astype( np.double)
def register_data(static_path, dynamic_path, output_path): path_new_displacement_fields = "{0}/new_displacement_fields/".format( output_path) if not os.path.exists(path_new_displacement_fields): os.makedirs(path_new_displacement_fields, mode=0o770) path_new_deformation_fields = "{0}/new_deformation_fields/".format( output_path) if not os.path.exists(path_new_deformation_fields): os.makedirs(path_new_deformation_fields, mode=0o770) path_new_tm = "{0}/new_tm/".format(output_path) if not os.path.exists(path_new_tm): os.makedirs(path_new_tm, mode=0o770) algo = reg.NiftyAladinSym() dvf_path = [] for i in range(len(dynamic_path)): ref = reg.ImageData(dynamic_path[i]) flo = reg.ImageData(static_path) algo.set_reference_image(ref) algo.set_floating_image(flo) algo.process() displacement_field = algo.get_displacement_field_forward() displacement_field.write("{0}/new_displacement_field_{1}.nii".format( path_new_displacement_fields, str(i))) dvf_path.append("{0}/new_DVF_field_{1}.nii".format( path_new_deformation_fields, str(i))) deformation_field = algo.get_deformation_field_forward() deformation_field.write(dvf_path[i]) tm = algo.get_transformation_matrix_forward() tm.write("{0}/new_tm_{1}.nii".format(path_new_tm, str(i))) return dvf_path
def test_for_adj(static_image, dvf_path, output_path): for i in range(len(dvf_path)): dvf_image = reg.NiftiImageData3DDeformation(dvf_path[i]) resampler = reg.NiftyResample() resampler.set_reference_image(static_image) resampler.set_floating_image(static_image) resampler.add_transformation(dvf_image) resampler.set_interpolation_type_to_cubic_spline() warp = warp_image_forward(resampler, static_image) warped_image = static_image.clone() warped_image.fill(warp) warped_image.write("{0}/warp_forward_{1}.nii".format( output_path, str(i))) difference = static_image.as_array().astype(np.double) - warp difference_image = static_image.clone() difference_image.fill(difference) difference_image.write("{0}/warp_forward_difference_{1}.nii".format( output_path, str(i))) warp = warp_image_adjoint(resampler, static_image) warped_image = static_image.clone() warped_image.fill(warp) warped_image.write("{0}/warp_adjoint_{1}.nii".format( output_path, str(i))) difference = static_image.as_array().astype(np.double) - warp difference_image = static_image.clone() difference_image.fill(difference) difference_image.write("{0}/warp_adjoint_difference_{1}.nii".format( output_path, str(i))) return True
def get_dynamic_data_magnitude(dynamic_path): dynamic_data_magnitude = 0.0 for i in range(len(dynamic_path)): dynamic_data_magnitude = dynamic_data_magnitude + np.nansum( reg.NiftiImageData(dynamic_path[i]).as_array().astype(np.double), dtype=np.double) return dynamic_data_magnitude
def resample_attn_image(image): """Resample the attenuation image.""" if trans_type == 'tm': transformation = reg.AffineTransformation(trans) elif trans_type == 'disp': transformation = reg.NiftiImageData3DDisplacement(trans) elif trans_type == 'def': transformation = reg.NiftiImageData3DDeformation(trans) else: raise ValueError("Unknown transformation type.") resampler = reg.NiftyResample() resampler.set_reference_image(image) resampler.set_floating_image(image) resampler.set_interpolation_type_to_linear() resampler.set_padding_value(0.0) resampler.add_transformation(transformation) return resampler.forward(image)
def get_resampler_from_tm(tm, image): """returns a NiftyResampler object for the specified transform matrix and image""" resampler = reg.NiftyResampler() resampler.set_reference_image(image) resampler.set_floating_image(image) resampler.add_transformation(tm) resampler.set_padding_value(0) resampler.set_interpolation_type_to_linear() return resampler
def gradient_function(optimise_array, resampler, dynamic_images, static_image, output_path): static_image.fill( np.reshape(optimise_array, static_image.as_array().astype(np.double).shape)) gradient_value = static_image.clone() gradient_value.fill(0.0) adjoint_image = static_image.clone() for i in range(len(dynamic_images)): static_image.write("{0}/temp_static.nii".format(output_path)) dynamic_images[i].write("{0}/temp_dynamic.nii".format(output_path)) temp_static = reg.NiftiImageData( "{0}/temp_static.nii".format(output_path)) temp_dynamic = reg.NiftiImageData( "{0}/temp_dynamic.nii".format(output_path)) adjoint_image.fill( warp_image_forward(resampler[i], temp_static) - temp_dynamic.as_array().astype(np.double)) gradient_value.fill((gradient_value.as_array().astype(np.double) + warp_image_adjoint(resampler[i], adjoint_image))) gradient_value.write("{0}/gradient.nii".format(output_path)) print( "Max gradient value: {0}, Min gradient value: {1}, Mean gradient value: {2}, Gradient norm: {3}" .format( str(gradient_value.as_array().astype(np.double).max()), str(gradient_value.as_array().astype(np.double).min()), str( np.nanmean(gradient_value.as_array().astype(np.double), dtype=np.double)), str(np.linalg.norm(gradient_value.as_array().astype(np.double))))) return np.ravel(gradient_value.as_array().astype(np.double)).astype( np.double)
def get_resampler(image, ref=None, trans=None): """returns a NiftyResampler object for the specified transform and image""" if ref is None: ref = image resampler = reg.NiftyResampler() resampler.set_reference_image(ref) resampler.set_floating_image(image) resampler.set_padding_value(0) resampler.set_interpolation_type_to_linear() if trans is not None: resampler.add_transformation(trans) return resampler
def back_warp(static_path, dvf_path, output_path): if not os.path.exists(output_path): os.makedirs(output_path, mode=0o770) for i in range(len(dvf_path)): static_image = reg.NiftiImageData(static_path) dvf_image = reg.NiftiImageData3DDeformation(dvf_path[i]) resampler = reg.NiftyResample() resampler.set_reference_image(static_image) resampler.set_floating_image(static_image) resampler.add_transformation(dvf_image) resampler.set_interpolation_type_to_cubic_spline() warped_static_image = warp_image_forward(resampler, static_image) static_image.fill(warped_static_image) static_image.write("{0}/back_warped_{1}.nii".format( output_path, str(i))) return True
def get_resamplers(static_image, dynamic_array, dvf_array): resamplers = [] for j in range(len(dynamic_array)): dynamic_image = dynamic_array[j] dvf_image = dvf_array[j] resampler = reg.NiftyResample() resampler.set_reference_image(static_image) resampler.set_floating_image(dynamic_image) resampler.add_transformation(dvf_image) resampler.set_interpolation_type_to_cubic_spline() resamplers.append(resampler) return resamplers
def transform_image(fixed_im_name, moving_im_name): """ Randomly transform 2D image by translation or rotation. fixed_im_name = """ trans_file = 'temp_trans_file.txt' angle = random.uniform(0, 1) tr_x = random.uniform(0, 1) tr_y = random.uniform(0, 1) theta = (angle - 0.5) * (math.pi / 2) #print('angle: {}\ntr_x: {}\ntr_y: {}\ntheta: {}'.format(angle, tr_x, tr_y, # theta)) transform = Reg.AffineTransformation( np.array([[math.cos(theta), -math.sin(theta), 0, (tr_x - 0.5) * 50], [math.sin(theta), math.cos(theta), 0, (tr_y - 0.5) * 50], [0, 0, 1, 0], [0, 0, 0, 1]])) transform.write(trans_file) # args = ["reg_resample", "-ref", "training_data/fixed/fixed_000.nii", # "-flo", "training_data/fixed/fixed_000.nii", "-res", "test", # "-trans", "temp_trans_file.txt"] # # popen = subprocess.Popen(args, stdout=subprocess.PIPE) # popen.wait() # args = [ "reg_resample", "-ref", fixed_im_name + '.nii', "-flo", fixed_im_name + '.nii', "-res", moving_im_name + '.nii', "-trans", trans_file ] popen = subprocess.Popen(args, stdout=subprocess.PIPE) popen.wait() os.remove(trans_file) return [-tr_x, -tr_y, -angle]
def get_and_save_tm(i): """Get and save affine transformation matrix""" if i == 0: [r, t_x, t_y] = [0., 0., 0.] elif i == 1: [r, t_x, t_y] = [10., -10., 0.] elif i == 2: [r, t_x, t_y] = [20., -5., 5.] elif i == 3: [r, t_x, t_y] = [-10., 10., 5.] else: [r, t_x, t_y] = [randint(-20, 20), randint(-20, 20), randint(-20, 20)] r = radians(r) tm = reg.AffineTransformation( np.array([[cos(r), sin(r), 0, t_x], [-sin(r), cos(r), 0, t_y], [0, 0, 1, 0], [0, 0, 0, 1]])) tm.write('fwd_tm_ms_' + str(i)) return tm
for i, sino, random in zip(range(len(path_sino)), sorted_alphanumeric(list_sino), sorted_alphanumeric(list_rando)): sino_pet = Pet.AcquisitionData(path_sino + sino) print(sino) randoms_pet = Pet.AcquisitionData(path_rando + random) print(random) # reconstruct the data (without mu-map) obj_fun = Pet.make_Poisson_loglikelihood(sino_pet) acq_model.set_background_term(randoms_pet) recon.set_objective_function(obj_fun) initial_image = sino_pet.create_uniform_image(1.0) image = initial_image recon.set_up(image) recon.set_current_estimate(image) recon.process() # save recon images recon_image = recon.get_output() recon_image.write(path_NAC + 'NAC_' + str(i)) # save Image as .nii recon_image = Reg.NiftiImageData(recon.get_output()) recon_image.write(path_NAC + 'NAC_' + str(i)) print('Reconstruction successful: Frame {}'.format(i)) tprint('Finish NAC Recon')
max_ring_diff=16, view_mash_factor=1) template_acq_data.write('template.hs') #%% resample mu-Map into correct space and transform via invers tm tprint('Start Resampling') attn_image = Pet.ImageData(attn_file) template_image = template_acq_data.create_uniform_image(1.0) # define space matrices tm_fwd = numpy.loadtxt(py_path + '/UKL_data/tm_epi/reg_NAC_EPI.txt') tm_inv = numpy.loadtxt(py_path + '/UKL_data/tm_epi/reg_NAC_EPI_inv.txt') # settings for attn resampler resamplers_attn = Reg.NiftyResample() resamplers_attn.set_reference_image(template_image) resamplers_attn.set_floating_image(attn_image) resamplers_attn.set_padding_value(0) resamplers_attn.set_interpolation_type_to_linear() i = 0 for num in num_tm: print('Begin resampling mu-Maps: {}'.format(path_EPI + 'tm_epi_inv_' + str(num) + '.txt')) # read tm-matrix as numpy array matrix = numpy.loadtxt(path_EPI + 'tm_epi_inv_' + str(num) + '.txt') # tm space transformation: EPI -> NAC # transform tm into PET space: T_nac = R⁻1 * T_epi * R
# change the current working directory to the given path os.chdir(working_folder) #%% Create folders for results path_EPI = working_folder + '/EPI/' if not os.path.exists(path_EPI): os.makedirs(path_EPI, mode=0o770) print('Create Folder: {}'.format(path_EPI)) #%% Registration EPI, delivers transformation matrices # define reference image (first image) and float-path tprint('Start Registration of EPIs') # refernce file epi_data_path = py_path + '/UKL_data/EPI/20190712/1/' ref_file = epi_data_path + 'epi_0.nii' ref = Eng_ref.ImageData(ref_file) # float files flo_path = epi_data_path # Niftyreg with EPI images reg_epi(ref, flo_path) tprint('Finish Registration')
if not os.path.exists(path_moco): os.makedirs(path_moco, mode=0o770) print('Create Folder: {}'.format(path_moco)) #%% resample the float images back to reference # list of all NACs list_NACs = [f for f in os.listdir(path_NAC) if f.endswith(".nii")] # list of all ACs list_ACs = [f for f in os.listdir(path_AC) if f.endswith(".nii")] # define reference image and float-path ref_file = path_AC + 'AC_0.nii' ref = Eng_ref.ImageData(ref_file) flo_path = path_AC # settings for image resampler resampler_im = Reg.NiftyResample() resampler_im.set_reference_image(ref) resampler_im.set_padding_value(0) resampler_im.set_interpolation_type_to_linear() tprint('Start Resampling') # for loop, simultaneous matrices and images for num, image in zip(range(len(list_ACs)), sorted_alphanumeric(list_ACs)): print('TM: {}, Float-Image: {}'.format('tm_nac_' + str(num) + '.txt', image)) flo = Eng_flo.ImageData(path_AC + image)
def optimise(input_data_path, data_split, weighted_normalise_path, input_dvf_path, dvf_split, output_path, do_op_test, do_reg, do_test_for_adj, do_blind_start, do_opt, do_back_warp, prefix): if not os.path.exists(output_path): os.makedirs(output_path, mode=0o770) new_dvf_path = "{0}/new_dvfs/".format(output_path) if not os.path.exists(new_dvf_path): os.makedirs(new_dvf_path, mode=0o770) # get static and dynamic paths dynamic_path = get_data_path(input_data_path, data_split) dynamic_data_magnitude = get_dynamic_data_magnitude(dynamic_path) static_path = "{0}/static_image.nii".format(output_path) # load static object for dvf registration static_image = reg.NiftiImageData(dynamic_path[0]) static_image.write(static_path) if do_op_test: op_test(static_image, output_path) dvf_path = None if do_test_for_adj or do_opt or do_back_warp: # if do reg the calc dvf if not load if do_reg: dvf_path = register_data(static_path, dynamic_path, output_path) else: dvf_path = get_dvf_path(input_dvf_path, dvf_split) # fix dvf header and load dvf objects dvf_path = edit_header(dvf_path, new_dvf_path) # sum the dynamic data into the static data for i in range(1, len(dynamic_path)): static_image.fill( static_image.as_array().astype(np.double) + reg.NiftiImageData(dynamic_path[i]).as_array().astype(np.double)) static_image.write(static_path) # test for adj if do_test_for_adj: test_for_adj(static_image, dvf_path, output_path) output_input(static_image, dynamic_path, dvf_path, output_path) # initial static image initial_static_image = static_image.clone() if do_blind_start: initial_static_image.fill(1.0) initial_static_image.write("{0}/initial_static_image_{1}.nii".format( output_path, prefix)) # array to optimise optimise_array = initial_static_image.as_array().astype(np.double) # array bounds bounds = [] for j in range(len(np.ravel(optimise_array))): bounds.append((0.01, 10.0)) tol = 0.000000000009 if do_opt: weighted_normalise = parser.parser(weighted_normalise_path, "weighted_normalise:=") if weighted_normalise is None: weighted_normalise = parser.parser(weighted_normalise_path, "normalise_array:=") for i in range(len(weighted_normalise)): weighted_normalise[i] = float(weighted_normalise[i]) # optimise optimise_array = np.reshape( scipy.optimize.minimize(objective_function, np.ravel(optimise_array), args=(static_image, dynamic_path, dvf_path, weighted_normalise, dynamic_data_magnitude), method="L-BFGS-B", jac=gradient_function, bounds=bounds, tol=tol, options={ "disp": True }).x, optimise_array.shape) # output static_image.fill(optimise_array) static_image.write("{0}/optimiser_output_{1}.nii".format( output_path, prefix)) difference = static_image.as_array().astype( np.double) - initial_static_image.as_array().astype(np.double) difference_image = initial_static_image.clone() difference_image.fill(difference) static_image.write("{0}/optimiser_output_difference_{1}.nii".format( output_path, prefix)) if do_back_warp: back_warp(static_path, dvf_path, "{0}/back_warp/".format(output_path)) multiple = 1.0 nan_optimise_array = optimise_array nan_optimise_array[nan_optimise_array < 0.01] = np.nan nan_optimise_array = nan_optimise_array - np.nanmin(nan_optimise_array) # array bounds bounds = [(0.01, 10.0)] # optimise multiple = scipy.optimize.minimize(suv_objective_function, np.asarray(multiple), args=(nan_optimise_array), method="L-BFGS-B", tol=tol, bounds=bounds, options={ "disp": True }).x[0] # output nan_optimise_array = nan_optimise_array - np.nanmin(nan_optimise_array) nan_optimise_array = np.nan_to_num(nan_optimise_array) nan_optimise_array[nan_optimise_array < 0.01] = 0.0 nan_optimise_array = nan_optimise_array * multiple static_image.fill(nan_optimise_array) static_image.write("{0}/suv_optimiser_output_{1}.nii".format( output_path, prefix)) naive_suv_optimise_array = optimise_array / 0.25 static_image.fill(naive_suv_optimise_array) static_image.write("{0}/naive_suv_optimiser_output_{1}.nii".format( output_path, prefix))
#%% create listmode-to-sinograms converter object lm2sino = Pet.ListmodeToSinograms() # set input, output and template files lm2sino.set_input(list_file) lm2sino.set_output_prefix(sino_file) lm2sino.set_template('template.hs') #%% from template sinogram, ensure that mu-map has spacing/offset # that matches the reconstructed image attn_image = Pet.ImageData(attn_file) template_image = template_acq_data.create_uniform_image(1.0) resampler = Reg.NiftyResample() resampler.set_reference_image(template_image) resampler.set_floating_image(attn_image) resampler.set_padding_value(0) resampler.set_interpolation_type_to_linear() attn_image = resampler.forward(attn_image) attn_image.write(working_folder + '/stir_mu_map_in_recon_space') #%% create folders for results path_sino = working_folder + '/sino' path_rando = working_folder + '/rando' path_recon = working_folder + '/recon' if not os.path.exists(path_sino): os.makedirs(path_sino, mode=0o770) print('Create Folder: {}'.format(path_sino))
shape = pet.EllipticCylinder() shape.set_length(1) shape.set_radii((random.uniform(1, image_shape[1] / 8), random.uniform(1, image_shape[2] / 8))) radii = shape.get_radii() shape.set_origin((0, random.uniform(-(image_shape[1] / 4) + radii[1], image_shape[1] / 4 - radii[1]), random.uniform(-(image_shape[2] / 4) + radii[0], image_shape[2] / 4 - radii[0]))) image.add_shape(shape, scale=random.uniform(0, 1)) image = add_noise(image) image = blur_image(image, 0.5) return image if __name__ == "__main__": initial_image = Reg.ImageData('blank_image.hv') print(initial_image.as_array().shape) image = generate_image(initial_image) plt.imshow(image.as_array()[0, :, :]) plt.show()