def setUp(self): self.image1 = pet.ImageData( os.path.join(examples_data_path('PET'), 'thorax_single_slice', 'emission.hv')) self.image2 = pet.ImageData( os.path.join(examples_data_path('PET'), 'thorax_single_slice', 'emission.hv'))
def get_x(input_path, input_prefix): print("Getting x") x = [] x_fixed = [] x_moving_fixed = [] relative_path = input_path + "/fixed/" x_fixed_files = os.listdir(relative_path) x_fixed_files.sort(key=human_sorting) print("Get x fixed") for i in range(len(x_fixed_files)): if len(x_fixed_files[i].split(input_prefix)) > 1: x_fixed.append( rescale_linear( PET.ImageData(relative_path + x_fixed_files[i]).as_array().squeeze(), 0, 1)) print("Got x fixed") relative_path = input_path + "/moving/" x_moving_files = os.listdir(relative_path) x_moving_files.sort(key=human_sorting) print("Get x moving") for i in range(len(x_moving_files)): temp_relative_path = relative_path + x_moving_files[i] + "/" x_moving_files_fixed_files = os.listdir(temp_relative_path) x_moving_files_fixed_files.sort(key=human_sorting) x_moving = [] for j in range(len(x_moving_files_fixed_files)): if len(x_moving_files_fixed_files[j].split(input_prefix)) > 1: x_moving.append( rescale_linear( PET.ImageData(temp_relative_path + x_moving_files_fixed_files[j]).as_array( ).squeeze(), 0, 1)) x_moving_fixed.append(x_moving) print("Got x moving") for i in range(len(x_moving_fixed)): for j in range(len(x_moving_fixed[i])): x.append(np.asarray([x_fixed[i], x_moving_fixed[i][j]]).T) print("Got x") return np.nan_to_num(np.asarray(x)).astype(np.float)
def get_asm_attn(sino, attn, acq_model): """Get attn ASM from sino, attn image and acq model.""" asm_attn = pet.AcquisitionSensitivityModel(attn, acq_model) # temporary fix pending attenuation offset fix in STIR: # converting attenuation into 'bin efficiency' asm_attn.set_up(sino) bin_eff = pet.AcquisitionData(sino) bin_eff.fill(1.0) asm_attn.unnormalise(bin_eff) asm_attn = pet.AcquisitionSensitivityModel(bin_eff) return asm_attn
def get_acquisition_model(uMap, templ_sino): """Create acquisition model""" am = pet.AcquisitionModelUsingRayTracingMatrix() am.set_num_tangential_LORs(5) # Set up sensitivity due to attenuation asm_attn = pet.AcquisitionSensitivityModel(uMap, am) asm_attn.set_up(templ_sino) bin_eff = pet.AcquisitionData(templ_sino) bin_eff.fill(1.0) asm_attn.unnormalise(bin_eff) asm_attn = pet.AcquisitionSensitivityModel(bin_eff) am.set_acquisition_sensitivity(asm_attn) am.set_up(templ_sino, uMap) return am
def main(): """Do main.""" # Acq model and template sino acq_model = pet.AcquisitionModelUsingRayTracingMatrix() acq_data = pet.AcquisitionData(sino_file) # If norm is present asm_norm = None if norm_e8_file: # create acquisition sensitivity model from ECAT8 normalisation data asm_norm = pet.AcquisitionSensitivityModel(norm_e8_file) # If attenuation is present asm_attn = None if attn_im_file: attn_image = pet.ImageData(attn_im_file) if trans: attn_image = resample_attn_image(attn_image) asm_attn = pet.AcquisitionSensitivityModel(attn_image, acq_model) # temporary fix pending attenuation offset fix in STIR: # converting attenuation into 'bin efficiency' asm_attn.set_up(acq_data) bin_eff = pet.AcquisitionData(acq_data) bin_eff.fill(1.0) print('applying attenuation (please wait, may take a while)...') asm_attn.unnormalise(bin_eff) asm_attn = pet.AcquisitionSensitivityModel(bin_eff) # Get ASM dependent on attn and/or norm if asm_norm and asm_attn: print("AcquisitionSensitivityModel contains norm and attenuation...") asm = pet.AcquisitionSensitivityModel(asm_norm, asm_attn) elif asm_norm: print("AcquisitionSensitivityModel contains norm...") asm = asm_norm elif asm_attn: print("AcquisitionSensitivityModel contains attenuation...") asm = asm_attn else: raise ValueError("Need norm and/or attn") # only need to project again if normalisation is added # (since attenuation has already been projected) if asm_norm: asm_attn.set_up(acq_data) bin_eff = pet.AcquisitionData(acq_data) bin_eff.fill(1.0) print('getting sinograms for multiplicative factors...') asm.set_up(acq_data) asm.unnormalise(bin_eff) print('writing multiplicative sinogram: ' + outp_file) bin_eff.write(outp_file)
def main(while_bool, generate_bool, fit_bool, test_bool, correct_bool): model = None while True: if generate_bool: print("Generate data") generate_data(PET.ImageData("blank_image.nii"), 1000, 1, "/home/alex/Documents/SIRF-SuperBuild_install/bin/stir_math", "/home/alex/Documents/SIRF-SuperBuild_install/bin/reg_resample") if fit_bool: print("Fit model") model = keras_reg.fit_model(model, False, True, True, False, "./training_data/", ".nii", "./results/", 1000) if test_bool: print("Test model") keras_reg.test_model(model, False, "./training_data/", ".nii", "./results/", "./results/") if correct_bool: print("Correct model") correct_data("/home/alex/Documents/SIRF-SuperBuild_install/bin/reg_resample", "./training_data/", "./corrected_data/", "./results/") if not while_bool: break
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 main(): initial_image = pet.ImageData('blank_image.hv') generate_data(initial_image, 100, 10) keras_reg.fit_model(False, False, True, "training_data/", ".nii", "results/")
def generate_image(initial_image): """ Add a random number of ellipsis to an initial image. """ image_shape = initial_image.as_array().shape image = initial_image.clone() for i in range(random.randint(2, 10)): 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
def get_elliptical_cylinder(radius_x, radius_y, length, origin=None): cyl = pet.EllipticCylinder() cyl.set_radius_x(radius_x) cyl.set_radius_y(radius_y) cyl.set_length(length) if origin is not None: cyl.set_origin(origin) return cyl
def test_BlockDataContainer_with_SIRF_DataContainer_subtract(self): os.chdir(self.cwd) image1 = pet.ImageData('emission.hv') image2 = pet.ImageData('emission.hv') image1.fill(2) image2.fill(1) print(image1.shape, image2.shape) bdc = BlockDataContainer(image1, image2) bdc1 = bdc.subtract(1.) image1.fill(1) image2.fill(0) bdc = BlockDataContainer(image1, image2) self.assertBlockDataContainerEqual(bdc, bdc1)
def test_BlockDataContainer_with_SIRF_DataContainer_multiply(self): os.chdir(self.cwd) image1 = pet.ImageData('emission.hv') image2 = pet.ImageData('emission.hv') image1.fill(1.) image2.fill(2.) print(image1.shape, image2.shape) tmp = image1.multiply(1.) numpy.testing.assert_array_equal(image1.as_array(), tmp.as_array()) tmp = image2.multiply(1.) numpy.testing.assert_array_equal(image2.as_array(), tmp.as_array()) # image.fill(1.) bdc = BlockDataContainer(image1, image2) bdc1 = bdc.multiply(1.) self.assertBlockDataContainerEqual(bdc, bdc1)
def setUp(self): path = os.path.join(examples_data_path('PET'), 'thorax_single_slice', 'template_sinogram.hs') if os.path.exists(path): template = pet.AcquisitionData(path) self.image1 = template.get_uniform_copy(0) self.image2 = template.get_uniform_copy(0) # assert False self.set_storage_scheme()
def setUp(self): data_path = os.path.join(examples_data_path('PET'), 'thorax_single_slice') image = pet.ImageData(os.path.join(data_path, 'emission.hv')) am = pet.AcquisitionModelUsingRayTracingMatrix() am.set_num_tangential_LORs(5) templ = pet.AcquisitionData( os.path.join(data_path, 'template_sinogram.hs')) am.set_up(templ, image) acquired_data = am.forward(image) obj_fun = pet.make_Poisson_loglikelihood(acquired_data) obj_fun.set_acquisition_model(am) obj_fun.set_up(image) self.obj_fun = obj_fun self.image = image
def test_main(rec=False, verb=False, throw=True): msg_red = pet.MessageRedirector() data_path = pet.examples_data_path('PET') raw_data_file = pet.existing_filepath(data_path, 'mMR/list.l.hdr') lm2sino = pet.ListmodeToSinograms() lm2sino.set_input(raw_data_file) num_prompts_threshold = 73036. known_time = 22. time_at_which_num_prompts_exceeds_threshold = \ lm2sino.get_time_at_which_num_prompts_exceeds_threshold(num_prompts_threshold) if abs(time_at_which_num_prompts_exceeds_threshold - known_time) > 1.e-4: raise AssertionError( "ListmodeToSinograms::get_time_at_which_num_prompts_exceeds_threshold failed" ) return 0, 1
def test_BlockDataContainer_with_SIRF_DataContainer_add(self): os.chdir(self.cwd) image1 = pet.ImageData('emission.hv') image2 = pet.ImageData('emission.hv') image1.fill(0) image2.fill(1) print(image1.shape, image2.shape) tmp = image1.add(1.) numpy.testing.assert_array_equal(image2.as_array(), tmp.as_array()) tmp = image2.subtract(1.) numpy.testing.assert_array_equal(image1.as_array(), tmp.as_array()) bdc = BlockDataContainer(image1, image2) bdc1 = bdc.add(1.) image1.fill(1) image2.fill(2) bdc = BlockDataContainer(image1, image2) self.assertBlockDataContainerEqual(bdc, bdc1)
def setUp(self): if os.path.exists( os.path.join(examples_data_path('PET'), 'mMR', 'mMR_template_span11_small.hs')): template = pet.AcquisitionData( os.path.join(examples_data_path('PET'), 'mMR', 'mMR_template_span11_small.hs')) self.image1 = template.get_uniform_copy(0) self.image2 = template.get_uniform_copy(0) # assert False self.set_storage_scheme()
def setUp(self): os.chdir(examples_data_path('PET')) #%% copy files to working folder and change directory to where the output files are shutil.rmtree('working_folder/thorax_single_slice',True) shutil.copytree('thorax_single_slice','working_folder/thorax_single_slice') os.chdir('working_folder/thorax_single_slice') image = pet.ImageData('emission.hv') am = pet.AcquisitionModelUsingRayTracingMatrix() am.set_num_tangential_LORs(5) templ = pet.AcquisitionData('template_sinogram.hs') am.set_up(templ,image) acquired_data=am.forward(image) obj_fun = pet.make_Poisson_loglikelihood(acquired_data) obj_fun.set_acquisition_model(am) obj_fun.set_up(image) self.obj_fun = obj_fun self.image = image
def get_image(): im_size = (127, 320, 320) im_spacing = (2.03125, 2.08626, 2.08626) image = pet.ImageData() image.initialise(im_size, im_spacing) image.fill(0) cyl = get_elliptical_cylinder(200, 100, 1000) image.add_shape(cyl, scale=0.75) cyl = get_elliptical_cylinder(100, 50, 300, (20, 30, 10)) image.add_shape(cyl, scale=3) cyl = get_elliptical_cylinder(10, 150, 700, (-20, 50, 50)) image.add_shape(cyl, scale=1.5) return image
def main(): # direct all engine's messages to files msg_red = PET.MessageRedirector('info.txt', 'warn.txt', 'errr.txt') PET.AcquisitionData.set_storage_scheme('memory') # Create the Scatter Estimator # We can use a STIR parameter file like this # par_file_path = os.path.join(os.path.dirname(__file__), '..', '..', 'parameter_files') # se = PET.ScatterEstimator(PET.existing_filepath(par_file_path, 'scatter_estimation.par')) # However, we will just use all defaults here, and set variables below. se = PET.ScatterEstimator() prompts = PET.AcquisitionData(raw_data_file) se.set_input(prompts) se.set_attenuation_image(PET.ImageData(mu_map_file)) if randoms_data_file is None: randoms = None else: randoms = PET.AcquisitionData(randoms_data_file) se.set_randoms(randoms) if not(norm_file is None): se.set_asm(PET.AcquisitionSensitivityModel(norm_file)) if not(acf_file is None): se.set_attenuation_correction_factors(PET.AcquisitionData(acf_file)) # could set number of iterations if you want to se.set_num_iterations(1) print("number of scatter iterations that will be used: %d" % se.get_num_iterations()) se.set_output_prefix(output_prefix) se.set_up() se.process() scatter_estimate = se.get_output() ## show estimated scatter data scatter_estimate_as_array = scatter_estimate.as_array() show_2D_array('Scatter estimate', scatter_estimate_as_array[0, 0, :, :]) ## let's draw some profiles to check # we will average over all sinograms to reduce noise PET_plot_functions.plot_sinogram_profile(prompts, randoms=randoms, scatter=scatter_estimate)
print('Norm data: {}'.format(norm_file)) #%% Create folders for results path_NAC = working_folder + '/recon/NAC/' path_sino = working_folder + '/sino/' path_rando = working_folder + '/rando/' if not os.path.exists(path_NAC): os.makedirs(path_NAC, mode=0o770) print('Create Folder: {}'.format(path_NAC)) #%% Settings for reconstruction # set acq_model acq_model = Pet.AcquisitionModelUsingRayTracingMatrix() acq_model.set_num_tangential_LORs(5) # set recon, OSEM recon = Pet.OSMAPOSLReconstructor() num_subsets = 7 num_subiterations = 4 recon.set_num_subsets(num_subsets) recon.set_num_subiterations(num_subiterations) # definitions for detector sensitivity modelling asm_norm = Pet.AcquisitionSensitivityModel(norm_file) acq_model.set_acquisition_sensitivity(asm_norm) #%% redirect STIR messages to some files # you can check these if things go wrong
# define the tm in the middle of the motion states num_tm = [] for time, dur in zip(time_intervals, time_frames): t = int(time / 2 + dur / 4) num_tm.append(t) print('Correct TM: {}'.format(num_tm)) #%% Files attn_file = py_path + '/UKL_data/mu_Map/stir_mu_map.hv' # .nii possible, requires ITK print('mu-Map: {}'.format(attn_file)) # template for acq_data template_acq_data = Pet.AcquisitionData('Siemens_mMR', span=11, 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()
def test_main(rec=False, verb=False, throw=True): pet.MessageRedirector() for scheme in ("file", "memory"): pet.AcquisitionData.set_storage_scheme(scheme) original_verb = pet.get_verbosity() pet.set_verbosity(False) # create an acq_model that is explicitly a RayTracingMatrix am = pet.AcquisitionModelUsingRayTracingMatrix() # load sample data data_path = pet.examples_data_path('PET') raw_data_file = pet.existing_filepath(data_path, 'Utahscat600k_ca_seg4.hs') ad = pet.AcquisitionData(raw_data_file) # create sample image image = pet.ImageData() image.initialise(dim=(31, 111, 111), vsize=(2.25, 2.25, 2.25)) # set up Acquisition Model am.set_up(ad, image) # test for adjointnesss if not is_operator_adjoint(am, verbose=verb): raise AssertionError( 'AcquisitionModelUsingRayTracingMatrix is not adjoint') # Reset original verbose-ness pet.set_verbosity(original_verb) return 0, 1
# # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # #========================================================================= import os, shutil, numpy import unittest import sirf.STIR as pet from sirf.Utilities import examples_data_path pet.AcquisitionData.set_storage_scheme('file') pet.set_verbosity(0) class TestSTIRObjectiveFunction(unittest.TestCase): def setUp(self): data_path = os.path.join(examples_data_path('PET'), 'thorax_single_slice') image = pet.ImageData(os.path.join(data_path, 'emission.hv')) am = pet.AcquisitionModelUsingRayTracingMatrix() am.set_num_tangential_LORs(5) templ = pet.AcquisitionData( os.path.join(data_path, 'template_sinogram.hs')) am.set_up(templ, image) acquired_data = am.forward(image)
convert = lambda text: int(text) if text.isdigit() else text.lower() alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)] return sorted(data, key=alphanum_key, reverse=False) # generate a list, contains the time intervalls (sum of frames) def sum_list(lists): sum_liste = [] add = int(0) sum_liste.append(add) for frame in lists[0:]: add += frame sum_liste.append(add) return sum_liste # Set the STIR verbosity Pet.set_verbosity(1) #%% data path and set filenames # data path to list-mode and normalisation files data_path_LM = '/home/rich/Documents/ReCo/UKL_data/LM/20190417/' data_path_MR = '/home/rich/Documents/ReCo/UKL_data/Processed/MedPhys_MoCo_Test_20190417_7/' # avoid cluttering of files, delete working-folder and start from scratch working_folder = '/home/rich/Documents/ReCo/working' if os.path.exists(working_folder): shutil.rmtree(working_folder) if not os.path.exists(working_folder): os.makedirs(working_folder, mode=0o770) # change the current working directory to the given path os.chdir(working_folder)
def main(): ## PET.AcquisitionData.set_storage_scheme('memory') # no info printing from the engine, warnings and errors sent to stdout msg_red = PET.MessageRedirector() # Create a template Acquisition Model #acq_template = AcquisitionData('Siemens mMR', 1, 0, 1) acq_template = PET.AcquisitionData( acq_template_filename) #q.get_uniform_copy() # create the attenuation image atten_image = PET.ImageData(acq_template) image_size = atten_image.dimensions() voxel_size = atten_image.voxel_sizes() # create a cylindrical water phantom water_cyl = PET.EllipticCylinder() water_cyl.set_length(image_size[0] * voxel_size[0]) water_cyl.set_radii((image_size[1]*voxel_size[1]*0.25, \ image_size[2]*voxel_size[2]*0.25)) water_cyl.set_origin((image_size[0] * voxel_size[0] * 0.5, 0, 0)) # add the shape to the image atten_image.add_shape(water_cyl, scale=9.687E-02) # z-pixel coordinate of the xy-crossection to show z = int(image_size[0] * 0.5) # show the phantom image atten_image_array = atten_image.as_array() show_2D_array('Attenuation image', atten_image_array[z, :, :]) # Create the activity image act_image = atten_image.clone() act_image.fill(0.0) # create the activity cylinder act_cyl = PET.EllipticCylinder() act_cyl.set_length(image_size[0] * voxel_size[0]) act_cyl.set_radii((image_size[1] * voxel_size[1] * 0.125, \ image_size[2] * voxel_size[2] * 0.125)) act_cyl.set_origin((0, image_size[1] * voxel_size[1] * 0.06, \ image_size[2] * voxel_size[2] * 0.06)) # add the shape to the image act_image.add_shape(act_cyl, scale=1) # z-pixel coordinate of the xy-crossection to show z = int(image_size[0] * 0.5) # show the phantom image act_image_array = act_image.as_array() show_2D_array('Activity image', act_image_array[z, :, :]) # Create the Single Scatter Simulation model sss = PET.SingleScatterSimulator() # Set the attenuation image sss.set_attenuation_image(atten_image) # set-up the scatter simulator sss.set_up(acq_template, act_image) # Simulate! sss_data = sss.forward(act_image) # show simulated scatter data simulated_scatter_as_array = sss_data.as_array() show_2D_array('scatter simulation', simulated_scatter_as_array[0, 0, :, :]) sss_data.write(output_file) ## let's also compute the unscattered counts (at the same low resolution) and compare acq_model = PET.AcquisitionModelUsingRayTracingMatrix() asm = PET.AcquisitionSensitivityModel(atten_image, acq_model) acq_model.set_acquisition_sensitivity(asm) acq_model.set_up(acq_template, act_image) #unscattered_data = acq_template.get_uniform_copy() unscattered_data = acq_model.forward(act_image) simulated_unscatter_as_array = unscattered_data.as_array() show_2D_array('unscattered simulation', simulated_unscatter_as_array[0, 0, :, :]) plt.figure() ax = plt.subplot(111) plt.plot(simulated_unscatter_as_array[0, 4, 0, :], label='unscattered') plt.plot(simulated_scatter_as_array[0, 4, 0, :], label='scattered') ax.legend() plt.show()
args = docopt(__doc__, version=__version__) # import engine module import sirf.STIR as PET import os from sirf.Utilities import show_2D_array # process command-line options data_file = args['--file'] data_path = args['--path'] print("FILE", __file__) if data_path is None: data_path = os.path.join(os.path.dirname(__file__), '..', '..', 'parameter_files') print(data_path) acq_template_filename = PET.existing_filepath(data_path, data_file) output_file = args['--output'] def main(): ## PET.AcquisitionData.set_storage_scheme('memory') # no info printing from the engine, warnings and errors sent to stdout msg_red = PET.MessageRedirector() # Create a template Acquisition Model #acq_template = AcquisitionData('Siemens mMR', 1, 0, 1) acq_template = PET.AcquisitionData( acq_template_filename) #q.get_uniform_copy() # create the attenuation image
def main(): initial_image = pet.ImageData('blank_image.hv') generate_data(initial_image, 10, 10)
def test_main(rec=False, verb=False, throw=True): # Set STIR verbosity to off original_verb = pet.get_verbosity() pet.set_verbosity(1) time.sleep(0.5) sys.stderr.write("Testing NiftyPET projector...") time.sleep(0.5) # Get image image = get_image() # Get AM try: acq_model = pet.AcquisitionModelUsingNiftyPET() except: return 1, 1 acq_model.set_cuda_verbosity(verb) data_path = examples_data_path('PET') # raw_data_path = pet.existing_filepath(os.path.join(data_path, 'mMR'), 'mMR_template_span11.hs') raw_data_path = os.path.join(data_path, 'mMR') template_acq_data = pet.AcquisitionData( os.path.join(raw_data_path, 'mMR_template_span11.hs')) acq_model.set_up(template_acq_data, image) # Test operator adjointness if verb: print('testing adjointness') if not is_operator_adjoint(acq_model, num_tests=1, verbose=True): raise AssertionError('NiftyPet AcquisitionModel is not adjoint') # Generate test data simulated_acq_data = acq_model.forward(image) simulated_acq_data_w_noise = add_noise(simulated_acq_data, 10) obj_fun = pet.make_Poisson_loglikelihood(template_acq_data) obj_fun.set_acquisition_model(acq_model) recon = pet.OSMAPOSLReconstructor() recon.set_objective_function(obj_fun) recon.set_num_subsets(1) recon.set_num_subiterations(1) recon.set_input(simulated_acq_data_w_noise) if verb: print('setting up, please wait...') initial_estimate = image.get_uniform_copy() recon.set_up(initial_estimate) if verb: print('reconstructing...') recon.set_current_estimate(initial_estimate) recon.process() reconstructed_im = recon.get_output() if not reconstructed_im: raise AssertionError() # Reset original verbose-ness pet.set_verbosity(original_verb) return 0, 1
flo_file = flo_path + image print(flo_file) flo = Eng_flo.ImageData(flo_file) nac_reg.set_floating_image(flo) nac_reg.process() tm_nac = nac_reg.get_transformation_matrix_forward() tm_nac_inv = nac_reg.get_transformation_matrix_inverse() tm_nac.write(path_tm + 'tm_nac_' + str(i)) tm_nac_inv.write(path_tm + 'tm_nac_inv_' + str(i)) i += 1 #%% Settings for reconstruction # set acq_model acq_model = Pet.AcquisitionModelUsingRayTracingMatrix() acq_model.set_num_tangential_LORs(5) # set recon, OSEM recon = Pet.OSMAPOSLReconstructor() num_subsets = 21 num_subiterations = 168 recon.set_num_subsets(num_subsets) recon.set_num_subiterations(num_subiterations) # dimensions nxny = (256, 256) #%% redirect STIR messages to some files # you can check these if things go wrong