Example #1
0
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)
Example #2
0
 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
Example #3
0
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
Example #4
0
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
Example #5
0
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
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
    matrix1 = numpy.matmul(tm_fwd, matrix)
    matrix2 = numpy.matmul(matrix1, tm_inv)

    # create affine transformation from numpy array
    tm = Reg.AffineTransformation(matrix2)

    resamplers_attn.clear_transformations()
    resamplers_attn.add_transformation(tm)
    new_attn = resamplers_attn.forward(attn_image)
    new_attn.write(path_mu + 'stir_mu_map_in_recon_space_' + str(i))
    Reg.ImageData(new_attn).write(path_mu + 'mu_' + str(i) + '.nii')

    print('Finish resampling mu-Maps: {}'.format(i))

    i += 1

tprint('Finish Resampling')
# 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)
Example #9
0
        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()
    print('Reconstruction successful: Frame {}'.format(i))

tprint('Finish Recon')


#%% create folder for motion corrected images
path_moco = working_folder + '/moco/'
if not os.path.exists(path_moco):
    os.makedirs(path_moco, mode=0o770)
    print('Create Folder: {}'.format(path_moco))


#%% convert a array to a SIRF transformation matrix and then resample the float image
# define reference image and float-path
ref_file = working_folder + '/floates/recon0.nii'
ref = Eng_ref.ImageData(ref_file)
flo_path = working_folder + '/floates/'

# path to folder, contain the MCFLIRT matrices
path_mat_mcflirt = frames_path + "epi_frames.mat/"

tprint('Start Reg')

# for loop, simultaneous matrices and images
for mat, image in zip(sorted(os.listdir(path_mat_mcflirt)), sorted_alphanumeric(os.listdir(flo_path))):
    print('TM: {}, Float-Image: {}'.format(mat, image))

    # read tm-matrix as numpy array and read load float image
    matrix = numpy.loadtxt(path_mat_mcflirt + mat)
    flo = Eng_flo.ImageData(flo_path + image)
Example #11
0
        smoothed_image = Reg.NiftiImageData(image)
        smoothed_image.write(path_smooth + 'smooth_' + str(i))

        print('Reconstruction successful: Frame {}'.format(i))

    tprint('Finish NAC Recon')

    #%% NAC registration
    # Registration NAC, delivers transformation matrices
    # define reference image (first image) and float-path

    tprint('Start Registration of NACs')

    # refernce file
    ref_file = path_smooth + 'smooth_0.nii'
    ref = Eng_ref.ImageData(ref_file)

    # float files
    flo_path = path_smooth
    list_smooth = [f for f in os.listdir(flo_path) if f.endswith(".nii")]

    # Niftyreg with EPI images
    reg_nac(ref, flo_path, list_smooth)

    tprint('Finish Registration')

    #%% resample mu-Map into NAC space and move it to each position

    ref_file = path_NAC + 'NAC_0.nii'
    ref = Eng_ref.ImageData(ref_file)
    flo = Eng_flo.ImageData(attn_image)
Example #12
0
                                        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 refernce
template_image = template_acq_data.create_uniform_image(1.0)

# EPI refernce file
epi_data_path = py_path + '/UKL_data/EPI/1/'
epi_file = epi_data_path + 'epi_0.nii'
epi = Eng_ref.ImageData(epi_file)

# 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')

tm_shift = numpy.loadtxt(py_path + '/UKL_data/tm_epi/tm_trans.txt')

# settings for attn resampler
resamplers_attn = Reg.NiftyResample()
resamplers_attn.set_reference_image(epi)
#resamplers_attn.set_floating_image(attn_image)
resamplers_attn.set_padding_value(0)
resamplers_attn.set_interpolation_type_to_linear()

i = 0
    print('Create Folder: {}'.format(path_rando))
if not os.path.exists(path_recon):
    os.makedirs(path_recon, mode=0o770)
    print('Create Folder: {}'.format(path_recon))
if not os.path.exists(path_NAC):
    os.makedirs(path_NAC, mode=0o770)
    print('Create Folder: {}'.format(path_NAC))
if not os.path.exists(path_moco_NAC):
    os.makedirs(path_moco_NAC, mode=0o770)
    print('Create Folder: {}'.format(path_moco_NAC))


#%% register EPI to PET with NiftyReg
ref_file = path_NAC + '/nii/' + 'NAC_0.nii'
flo_file = data_path_UTE_image
ref = Eng_ref.ImageData(ref_file)
flo = Eng_ref.ImageData(flo_file)

# register = Reg.NiftyAladinSym()
# register.set_reference_image(ref)
# register.set_floating_image(flo)
# register.set_parameter("SetPerformRigid", "1")
# register.set_parameter("SetPerformAffine", "0")
# register.process()
# tm_fwd = register.get_transformation_matrix_forward()
# tm_fwd.write(working_folder + '/tm_fwd.txt')
# tm_inv = register.get_transformation_matrix_inverse()
# tm_inv.write(working_folder + '/tm_inv.txt')
# temp = register.get_output()
# temp.write(working_folder + 'UTE_PET_space.nii')
#
Example #14
0
import sirf.Reg as reg
import matplotlib.pyplot as plt
import numpy as np

import pet_vis_utils as petvis



# Load 2 3D images:
my_data_path=""
img1=reg.ImageData(my_data_path)
img2=reg.ImageData(my_data_path2)
img1=img1.as_array()
img2=img2.as_array()
#Load a displacement vector field
dvf=reg.NiftiImageData3DDisplacement(my_dvf_pat)
dvf=dvf.as_array()


# Plot MIP
plt.figure()
plt.subplot(1,2,1)
petvis.imshow(np.flip(petvis.MIP(img1),axis=0),limits=[], title= 'Image 1',colormap="Greys")
plt.subplot(1,2,2)
petvis.imshow(np.flip(petvis.MIP(img2),axis=0),limits=[0, 1], title='Image 2',colormap="Greys")
plt.show()

# Plot 3D image
plt.figure()
petvis.imshow3D([img1,img2],limits=[0, 5e4], title=['Image 1', 'Image 2'],colormap="Greys")
# alternatively: imshow3D(img1,limits=[0, 5e4], title='Image 1',colormap="Greys")
    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 + '/nii/NAC_' + str(i))

    print('Reconstruction successful: Frame {}'.format(i))

tprint('Finish Recon NAC')


#%% SPM registration NAC
# define reference image (first image) and float-path, NAC
ref_file = path_NAC + '/nii/' + 'NAC_0.nii'
ref = Eng_ref.ImageData(ref_file)
flo_path = path_NAC + '/nii/'

tprint('Start Reg for NAC')

# SPM, NAC images
spm_reg = Reg.SPMRegistration()
spm_reg.set_reference_image(ref)
for image in sorted_alphanumeric(os.listdir(flo_path)):
    flo_file = flo_path + image
    flo = Eng_ref.ImageData(flo_file)
    spm_reg.add_floating_image(flo)
spm_reg.set_working_folder(path_moco_NAC)
spm_reg.set_working_folder_file_overwrite(True)
spm_reg.set_delete_temp_files(True)
spm_reg.process()
Example #16
0
# avoid cluttering of files, delete working-folder and start from scratch
working_folder = '/home/rich/Documents/ReCo/working2'
#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)


#%% define ref and float images
# ref = float, for motion simulation
ref_file = recon_file
ref = Eng_ref.ImageData(ref_file)

flo_file = recon_file
flo = Eng_flo.ImageData(flo_file)


#%% define motion parameters
# rotation
xC, xS = trig(0)
yC, yS = trig(0)
zC, zS = trig(30)

# translation
dX = 0
dY = 0
dZ = 0