Exemple #1
0
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
Exemple #2
0
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)
Exemple #3
0
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
Exemple #4
0
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
Exemple #5
0
def get_resampler_from_tm(tm, image):
    """returns a NiftyResample object for the specified transform matrix and image"""
    resampler = reg.NiftyResample()
    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
Exemple #6
0
def get_resampler(image, ref=None, trans=None):
    """returns a NiftyResample object for the specified transform and image"""
    if ref is None:
        ref = image
    resampler = reg.NiftyResample()
    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
Exemple #7
0
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
Exemple #8
0
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)
Exemple #9
0
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
Exemple #10
0
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
Exemple #11
0
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)
Exemple #12
0
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
                                        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
#%% 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)

    # read tm-matrix as numpy array
    matrix = numpy.loadtxt(path_tm + 'tm_nac_' + str(num) + '.txt')
  
#%% 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))
Exemple #16
0
def try_complex_resample(raw_mr_filename):
    time.sleep(0.5)
    sys.stderr.write('\n# --------------------------------------------------------------------------------- #\n')
    sys.stderr.write('#                             Starting complex resampling test...\n')
    sys.stderr.write('# --------------------------------------------------------------------------------- #\n')
    time.sleep(0.5)

    raw_mr = mr.AcquisitionData(raw_mr_filename)

    recon_gadgets = ['NoiseAdjustGadget',
                     'AsymmetricEchoAdjustROGadget',
                     'RemoveROOversamplingGadget',
                     'AcquisitionAccumulateTriggerGadget(trigger_dimension=repetition)',
                     'BucketToBufferGadget(split_slices=true, verbose=false)',
                     'SimpleReconGadget',
                     'ImageArraySplitGadget']

    recon = mr.Reconstructor(recon_gadgets)
    recon.set_input(raw_mr)
    recon.process()

    ismrmrd_im = recon.get_output()

    if ismrmrd_im.is_real():
        raise AssertionError("Expected output of reconstruction to be complex")

    # Complex component may be empty, so use imag = real / 2
    image_data_arr = ismrmrd_im.as_array()
    image_data_arr.imag = image_data_arr.real / 2
    ismrmrd_im.fill(image_data_arr)

    # Convert the complex image to two niftis
    [real, imag] = reg.ImageData.construct_from_complex_image(ismrmrd_im)
    real.write("results/real")
    imag.write("results/imag")

    # Create affine transformation
    tm = reg.AffineTransformation()
    tm_ = tm.as_array()
    tm_[0][3] = 2.
    tm = reg.AffineTransformation(tm_)

    # Resample the complex data
    res_complex = reg.NiftyResample()
    res_complex.set_reference_image(ismrmrd_im)
    res_complex.set_floating_image(ismrmrd_im)
    res_complex.set_interpolation_type_to_linear()
    res_complex.add_transformation(tm)
    forward_cplx_sptr = res_complex.forward(ismrmrd_im)
    adjoint_cplx_sptr = res_complex.adjoint(ismrmrd_im)

    # Get the output
    [forward_cplx_real, forward_cplx_imag] = \
        reg.ImageData.construct_from_complex_image(forward_cplx_sptr)
    [adjoint_cplx_real, adjoint_cplx_imag] = \
        reg.ImageData.construct_from_complex_image(adjoint_cplx_sptr)

    forward_cplx_real.write("results/forward_cplx_real")
    forward_cplx_imag.write("results/forward_cplx_imag")
    adjoint_cplx_real.write("results/adjoint_cplx_real")
    adjoint_cplx_imag.write("results/adjoint_cplx_imag")

    # Now resample each of the components individually
    res_real = reg.NiftyResample()
    res_real.set_reference_image(real)
    res_real.set_floating_image(real)
    res_real.set_interpolation_type_to_linear()
    res_real.add_transformation(tm)
    forward_real = res_real.forward(real)
    adjoint_real = res_real.adjoint(real)

    res_imag = reg.NiftyResample()
    res_imag.set_reference_image(imag)
    res_imag.set_floating_image(imag)
    res_imag.set_interpolation_type_to_linear()
    res_imag.add_transformation(tm)
    forward_imag = res_imag.forward(imag)
    adjoint_imag = res_imag.adjoint(imag)

    forward_real.write("results/forward_real")
    forward_imag.write("results/forward_imag")
    adjoint_real.write("results/adjoint_real")
    adjoint_imag.write("results/adjoint_imag")

    # Compare that the real and imaginary parts match regardless
    # of whether they were resampled separately or together.
    if forward_real != forward_cplx_real or forward_imag != forward_cplx_imag:
        raise AssertionError("NiftyResample::forward failed for complex data")
    if adjoint_real != adjoint_cplx_real or adjoint_imag != adjoint_cplx_imag:
        raise AssertionError("NiftyResample::adjoint failed for complex data")

    time.sleep(0.5)
    sys.stderr.write('\n# --------------------------------------------------------------------------------- #\n')
    sys.stderr.write('#                             Finished complex resampling test.\n')
    sys.stderr.write('# --------------------------------------------------------------------------------- #\n')
    time.sleep(0.5)