Beispiel #1
0
def Registration(dir_res, fixed_image_path, moving_image_path, parameter_path, ELASTIX_PATH, pnr, anr, method, init):
    "Function to registrate one moving on one fixed image. pnr should be given as 'p102'"
    
    # Make a results folder if non exists (in Codes_def folder)
    
    if init:
        output = dir_res+'results_{}_{}/'.format(method, pnr)
        output_dir = output+'atlas_{}'.format(anr)
        if os.path.exists(output) is False:
            os.mkdir(output)
        if os.path.exists(output_dir) is False:
            os.mkdir(output_dir)
        
    else:
        output = dir_res+'results_{}/'.format(pnr)
        output_dir = output+'atlas_{}'.format(anr)
        if os.path.exists(output) is False:
            os.mkdir(output)
        if os.path.exists(output_dir) is False:
            os.mkdir(output_dir)
        
    el = elastix.ElastixInterface(elastix_path=ELASTIX_PATH)
    el.register(
        fixed_image=fixed_image_path,
        moving_image=moving_image_path,
        parameters=[parameter_path],
        output_dir=output_dir)
    return output_dir
Beispiel #2
0
def get_el(ELASTIX_PATH):
    if not os.path.exists(ELASTIX_PATH):
        raise IOError(
            'Elastix cannot be found, please set the correct ELASTIX_PATH.')
    # Define a new elastix object 'el' with the correct path to elastix
    el = elastix.ElastixInterface(elastix_path=ELASTIX_PATH)
    return el
def Registration(fixed_image_path, atlas_path, ELASTIX_PATH, pnr):
    "Function does registration for one atlas with one fixed image"

    parameter_file_path = r'TrainingData\parameters.txt'

    # Make a results directory if non exists
    if os.path.exists('results_{}'.format(pnr)) is False:
        os.mkdir('results_{}'.format(pnr))

    el = elastix.ElastixInterface(elastix_path=ELASTIX_PATH)
    el.register(fixed_image=fixed_image_path,
                moving_image=atlas_path,
                parameters=[parameter_file_path],
                output_dir='results_{}'.format(pnr))
Beispiel #4
0
def Registration(fixed_image_path, atlas_path, parameter_path, ELASTIX_PATH,
                 pnr):
    "Function to registrate one atlas on one fixed image. pnr should be given as 'p102'"

    # Make a results directory if non exists
    if os.path.exists('Results/results_{}'.format(pnr)) is False:
        os.mkdir('Results/results_{}'.format(pnr))

    el = elastix.ElastixInterface(elastix_path=ELASTIX_PATH)
    output_dir = 'Results/results_{}'.format(pnr)
    el.register(fixed_image=fixed_image_path,
                moving_image=atlas_path,
                parameters=[parameter_path],
                output_dir=output_dir)
    return output_dir
Beispiel #5
0
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
Beispiel #6
0
def BSplineOnly(f, m, p, path, elastix_path, output, plot=False):
    "Peforms BSpline transformation, using the fixed image, moving image, provided parameter file"
    E = elastix.ElastixInterface(elastix_path)
    E.register(fixed_image=f,
               moving_image=m,
               parameters=[p],
               output_dir=output)
    if plot == True:
        for i in range(4):
            L = elastix.logfile('{}\IterationInfo.0.R{}.txt'.format(path, i))
            # Plot the 'metric' against the iteration number 'itnr'
            plt.figure()
            plt.plot(L['itnr'], L['metric'])
            plt.tight_layout()
            plt.xlabel('Iteration Number', size=16)
            plt.ylabel('Mattes Mutual Information', size=16)
            plt.xticks(size=14)
            plt.yticks(size=14)
Beispiel #7
0
unseen_index = patients.index(unseen)

unseen_folder = 'results{}'.format(unseen)
# Make a results directory if non exists
if not os.path.exists(unseen_folder):
    os.mkdir(unseen_folder)

# Get unseen mri and segmentations
unseen_image_path = os.path.join(unseen, 'mr_bffe.mhd')
image_array_unseen = sitk.GetArrayFromImage(sitk.ReadImage(unseen_image_path))

opr_image_path = os.path.join(unseen, 'prostaat.mhd')
image_array_opr = sitk.GetArrayFromImage(sitk.ReadImage(opr_image_path))

# Define a new elastix object 'el' with the correct path to elastix
el = elastix.ElastixInterface(elastix_path=ELASTIX_PATH)

DSC = []
SNS = []
SPC = []
finalMI = []

# Execute the registrations.
for i, patient in enumerate(patients):

    # Reading patient segmentation and mri
    pr_image_path = os.path.join(patient, 'prostaat.mhd')
    mr_image_path = os.path.join(patient, 'mr_bffe.mhd')

    # Everything for this registration will be put in result_path
    pat_folder = 'result_unseen{}_{}'.format(unseen, patient)
Beispiel #8
0
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
Beispiel #9
0
#visualisation commands
#visualize2d(fixednr,movingnr,slicenr,runnr)
#visualize3d(fixednr,movingnr,slicenr,runnr)

fixedmask = findfixedmask(107)
transformedmask = findtransformedmask(runnr)

print(medpyDC(transformedmask, fixedmask))
print(medpyHD(transformedmask, fixedmask))

fixed_image_path = os.path.join(f"results{runnr}", "result.mhd")
moving_image_path = os.path.join(data_path, f"p{movingnr}\mr_bffe.mhd")

output_dir = f'results{runnr}'

el = elastix.ElastixInterface(elastix_path=elastix_path)

#run model
el.register(fixed_image=fixed_image_path,
            moving_image=moving_image_path,
            parameters=[parameter_file2],
            output_dir=output_dir)

transformedmask2 = findtransformedmask(runnr)

print(medpyDC(transformedmask, fixedmask))
print(medpyHD(transformedmask, fixedmask))
print(medpyDC(transformedmask2, fixedmask))
print(medpyHD(transformedmask2, fixedmask))
Beispiel #10
0
#
#im1 = r'C:\Users\s081992\Documents\TUE\Year 2\Q3\Capita Selecta\Part 2\PracticalSession2019 2\PracticalSession2019\chest_xrays\moving_image.mhd'
#im2 = r'C:\Users\s081992\Documents\TUE\Year 2\Q3\Capita Selecta\Part 2\PracticalSession2019 2\PracticalSession2019\chest_xrays\fixed_image.mhd'

im1 = 'C:\\Users\\s081992\\Documents\\TUE\\Year 2\\Q3\\Capita Selecta\\Part 2\\TrainingData\\TrainingData\\p102\\mr_bffe.mhd'
im2 = 'C:\\Users\\s081992\\Documents\\TUE\\Year 2\\Q3\\Capita Selecta\\Part 2\\TrainingData\\TrainingData\\p107\\mr_bffe.mhd'

#im1 = 'C:\\Users\\s081992\\Documents\\TUE\\Year 2\\Q3\\Capita Selecta\\Part 2\\TrainingData\\TrainingData\\p102\\prostaat.mhd'
#im2 = 'C:\\Users\\s081992\\Documents\\TUE\\Year 2\\Q3\\Capita Selecta\\Part 2\\TrainingData\\TrainingData\\p107\\prostaat.mhd'

#im1raw = r'C:\Users\s081992\Documents\TUE\Year 2\Q3\Capita Selecta\Part 2\PracticalSession2019 2\PracticalSession2019\chest_xrays\moving_image.raw'
#im2raw = r'C:\Users\s081992\Documents\TUE\Year 2\Q3\Capita Selecta\Part 2\PracticalSession2019 2\PracticalSession2019\chest_xrays\fixed_image.raw'

# Define a new elastix object 'E' with the CORRECT PATH to elastix
E = elastix.ElastixInterface(
    elastix_path=
    r'C:\Users\s081992\Documents\TUE\Year 2\Q3\Capita Selecta\Part 2\PracticalSession2019 2\PracticalSession2019\Software\Software\elastix_windows64_v4.7\elastix.exe'
)

# Execute the registration. Make sure the paths below are correct, and
# that the results folder exists from where you are running this script

#%%

#path = r'C:\Users\s081992\Documents\TUE\Year 2\Q3\Capita Selecta\Part 2\TrainingData\TrainingData\p102\mr_bffe.mhd'
#image = sitk.ReadImage(path)
#as_array = sitk.GetArrayFromImage(image)
#
#
#
#import SimpleITK as sitk
#image = sitk.ReadImage(im1raw)