def correlation_test(): I = plt.imread('../data/t1_demo.tif') Th = util.t2h(reg.identity(), np.array([10, 20])) J, _ = reg.image_transform(I, Th) K, _ = reg.image_transform(J, Th) C1 = reg.correlation(I, I) C2 = reg.correlation(J, J) # the self correlation should be very close to 1 assert abs( C1 - 1 ) < 10e-10, "Correlation function is incorrectly implemented (self correlation test)" assert abs( C2 - 1 ) < 10e-10, "Correlation function is incorrectly implemented (self correlation test)" C3 = reg.correlation(I, J) C4 = reg.correlation(I, K) print("Correlation between images with slight translocation:", C3) print("Correlation between images with big translocation:", C4, "\n") print('Test successful!') ######## print("\n\nAnd now for a test on the joint probability histogram: \n") p = reg.joint_histogram(I, J) assert abs(1 - float(np.sum(p))) < 0.01, "Mass probability function error..." print("Test successful!")
def correlation_test(): I = plt.imread('../data/cameraman.tif') Th = util.t2h(reg.identity(), np.array([10, 20])) J, _ = reg.image_transform(I, Th) C1 = reg.correlation(I, I) # the self correlation should be very close to 1 assert abs( C1 - 1 ) < 10e-10, "Correlation function is incorrectly implemented (self correlation test)" #------------------------------------------------------------------# # TODO: Implement a few more tests of the correlation definition #correlation when two signals are exaclty opposite should be very close to -1 C2 = reg.correlation(I, -I) assert abs( C2 + 1 ) < 10e-10, "Correlation function is incorrectly implemented (opposite self correlation test)" #detect corrrelation of two signals with different amplitudes should be 1 C3 = reg.correlation(I, I / 2) assert abs( C3 - 1 ) < 10e-10, "Correlation function is incorrectly implemented (different amplitude self correlation test)" C4 = reg.correlation(I, J) print(C4) assert abs( C4 - 1 ) < 10e-1, "Correlation function is incorrectly implemented (two diff images no correlation)" #------------------------------------------------------------------# print('Test successful!')
def correlation_test(): I = plt.imread('../data/cameraman.tif') Th = util.t2h(reg.identity(), np.array([10, 20])) J, _ = reg.image_transform(I, Th) C1 = reg.correlation(I, I) # the self correlation should be very close to 1 assert abs( C1 - 1 ) < 10e-10, "Correlation function is incorrectly implemented (self correlation test)" C2 = reg.correlation(I, -I) print('Test successful!')
def affine_corr(I, Im, x, MI): # Computes normalized cross-correlation between a fixed and # a moving image transformed with an affine transformation. # Input: # I - fixed image # Im - moving image # x - parameters of the rigid transform: the first element # is the rotation angle, the second and third are the # scaling parameters, the fourth and fifth are the # shearing parameters and the remaining two elements # are the translation # Output: # C - normalized cross-correlation between I and T(Im) # Im_t - transformed moving image T(Im) Tro = reg.rotate(x[0]) Tsc = reg.scale(x[1], x[2]) Tsh = reg.shear(x[3], x[4]) Trss = Tro.dot(Tsc).dot(Tsh) Th = util.t2h(Trss, [x[5], x[6]]) Im_t, Xt = reg.image_transform(Im, Th) if MI: p = joint_histogram(I, Im_t) S = reg.mutual_information(p) else: S = reg.correlation(I, Im_t) return S, Im_t, Th
def rigid_corr(I, Im, x, MI): # Computes normalized cross-correlation between a fixed and # a moving image transformed with a rigid transformation. # Input: # I - fixed image # Im - moving image # x - parameters of the rigid transform: the first element # is the rotation angle and the remaining two elements # are the translation # Output: # C - normalized cross-correlation between I and T(Im) # Im_t - transformed moving image T(Im) SCALING = 100 # the first element is the rotation angle T = reg.rotate(x[0]) Th = util.t2h(T, x[1:] * SCALING) # transform the moving image Im_t, Xt = reg.image_transform(Im, Th) # compute the similarity between the fixed and transformed moving image if MI: p = joint_histogram(I, Im_t) S = reg.mutual_information(p) else: S = reg.correlation(I, Im_t) return S, Im_t, Th
def correlation_test(): I = plt.imread('../data/cameraman.tif') Th = util.t2h(reg.identity(), np.array([10, 20])) J, _ = reg.image_transform(I, Th) error_msg = "Correlation function is incorrectly implemented" C1 = reg.correlation(I, I) C2 = reg.correlation(I, J) C3 = reg.correlation(I, np.ones_like(I)) # the self correlation should be very close to 1 assert abs(C1 - 1) < 10e-10, error_msg + " (self correlation should be 1)" assert C1 >= -1, error_msg + " (self correlation is should be more than -1)" assert C2 <= 1, error_msg + " (translation correlation should be less than 1)" assert C2 >= -1, error_msg + " (translation correlation should be more than -1)" print('Correlation test successful!')
def correlation_test(): I = plt.imread('../data/cameraman.tif') Th = util.t2h(reg.identity(), np.array([10, 20])) J, _ = reg.image_transform(I, Th) C1 = reg.correlation(I, I) # the self correlation should be very close to 1 assert abs( C1 - 1 ) < 10e-10, "Correlation function is incorrectly implemented (self correlation test)" #------------------------------------------------------------------# # TODO: Implement a few more tests of the correlation definition C2 = reg.correlation(I, J) print(C1, C2)
def correlation_test(): I = plt.imread('../data/cameraman.tif') Th = util.t2h(reg.identity(), np.array([10, 20])) J, _ = reg.image_transform(I, Th) C1 = reg.correlation(I, I) # the self correlation should be very close to 1 assert abs( C1 - 1 ) < 10e-10, "Correlation function is incorrectly implemented (self correlation test)" #------------------------------------------------------------------# # Implement a few more tests of the correlation definition I1 = plt.imread('../data/t1_demo.tif') I2 = plt.imread('../data/t2_demo.tif') C2 = reg.correlation(I1, I1) print('C2:', C2) C3 = reg.correlation(I1, I2) print('C3:', C3) #------------------------------------------------------------------# print('Test successful!')
def optim_affine_corr(x, I, Im, MI): # Identical to affine_corr in functionality but the x variable is placed # in front when calling for use in scipy.optimize function. # Output is changed to only give the similarity because scipy.optimize # uses this metric to optimize the parameters Tro = reg.rotate(x[0]) Tsc = reg.scale(x[1], x[2]) Tsh = reg.shear(x[3], x[4]) Trss = Tro.dot(Tsc).dot(Tsh) Th = util.t2h(Trss, [x[5], x[6]]) Im_t, Xt = reg.image_transform(Im, Th) if MI: p = joint_histogram(I, Im_t) S = reg.mutual_information(p) else: S = reg.correlation(I, Im_t) return S
def optim_rigid_corr(x, I, Im, MI): # Identical to rigid_corr in functionality but the x variable is placed # in front when calling for use in scipy.optimize function. # Output is changed to only give the similarity because scipy.optimize # uses this metric to optimize the parameters SCALING = 100 # the first element is the rotation angle T = reg.rotate(x[0]) Th = util.t2h(T, x[1:] * SCALING) # transform the moving image Im_t, Xt = reg.image_transform(Im, Th) # compute the similarity between the fixed and transformed moving image if MI: p = joint_histogram(I, Im_t) S = reg.mutual_information(p) else: S = reg.correlation(I, Im_t) return S
def registration_metrics_demo(use_t2=False): # read a T1 image I = plt.imread('../data/t1_demo.tif') if use_t2: # read the corresponding T2 image # note that the T1 and T2 images are already registered I_t2 = plt.imread('../data/t2_demo.tif') # create a linear space of rotation angles - 101 angles between 0 and 360 deg. angles = np.linspace(-np.pi, np.pi, 101, endpoint=True) CC = np.full(angles.shape, np.nan) MI = np.full(angles.shape, np.nan) # visualization fig = plt.figure(figsize=(14,6)) # correlation ax1 = fig.add_subplot(131, xlim=(-np.pi, np.pi), ylim=(-1.1, 1.1)) line1, = ax1.plot(angles, CC, lw=2) ax1.set_xlabel('Rotation angle') ax1.set_ylabel('Correlation coefficient') ax1.grid() # mutual mutual_information ax2 = fig.add_subplot(132, xlim=(-np.pi, np.pi), ylim=(0, 2)) line2, = ax2.plot(angles, MI, lw=2) ax2.set_xlabel('Rotation angle') ax2.set_ylabel('Mutual information') ax2.grid() # images ax3 = fig.add_subplot(133) im1 = ax3.imshow(I) im2 = ax3.imshow(I, alpha=0.7) # used for rotation around image center t = np.array([I.shape[0], I.shape[1]])/2 + 0.5 T_1 = util.t2h(reg.identity(), t) T_3 = util.t2h(reg.identity(), -t) # loop over the rotation angles for k, ang in enumerate(angles): # transformation matrix for rotating the image # I by angles(k) around its center point T_2 = util.t2h(reg.rotate(ang), np.zeros(2)) T_rot = T_1.dot(T_2).dot(T_3) if use_t2: # rotate the T2 image J, Xt = reg.image_transform(I_t2, T_rot) else: # rotate the T1 image J, Xt = reg.image_transform(I, T_rot) # compute the joint histogram with 16 bins p = reg.joint_histogram(I, J, 16, [0, 255]) CC[k] = reg.correlation(I, J) MI[k] = reg.mutual_information(p) clear_output(wait = True) # visualize the results line1.set_ydata(CC) line2.set_ydata(MI) im2.set_data(J) display(fig)
""" Part 2: T1 and T2 """ ##choose fiducial points and save them for T1 and T1 moving X1, X2 = util.my_cpselect(I1_path, I2_path) Th2, fig2, It2 = proj.point_based_registration(I1_path, I2_path, X1, X2) np.save( path + "/transformation_matrix_T1_and_T2_moving_" + str(numberofpoints), Th2) plt.savefig(path + "/transformed_T2_image_" + str(numberofpoints) + ".png") #calculate correlation display("Calculate correlation") corr_I2 = reg.correlation(I1, It2) #calculate mutual information display("Calculate mutual information") p2 = reg.joint_histogram(I1, It2) mi_I2 = reg.mutual_information(p2) """ Evaluation of point-based affine image registration """ #Calculate the registration error for T1 and T1 moving # ##Select target points for T1 and T1 moving #X1_target, Xm1_target = util.my_cpselect(I1_path, Im1_path) # #Reg_error1 = proj.Evaluate_point_based_registration(T1, X1_target, Xm1_target) #print('Registration error for pair of T1 image slices:\n{}'.format(Reg_error1))
def rigid_corr_adapted(I, Im, x): #ADAPTED: In order to determine the gradient of the parameters, you only #need the correlation value. So, the outputs: Th and Im_t are removed. #Nothing else is changed. #Attention this function will be used for ngradient in the function: #intensity_based_registration_rigid_adapted. # Computes normalized cross-correlation between a fixed and # a moving image transformed with a rigid transformation. # Input: # I - fixed image # Im - moving image # x - parameters of the rigid transform: the first element # is the rotation angle and the remaining two elements # are the translation # Output: # C - normalized cross-correlation between I and T(Im) # Im_t - transformed moving image T(Im) SCALING = 100 # the first element is the rotation angle T = reg.rotate(x[0]) # the remaining two element are the translation # # the gradient ascent/descent method work best when all parameters # of the function have approximately the same range of values # this is not the case for the parameters of rigid registration # where the transformation matrix usually takes much smaller # values compared to the translation vector this is why we pass a # scaled down version of the translation vector to this function # and then scale it up when computing the transformation matrix Th = util.t2h(T, x[1:] * SCALING) # transform the moving image Im_t, Xt = reg.image_transform(Im, Th) # compute the similarity between the fixed and transformed # moving image C = reg.correlation(I, Im_t) return C
def affine_corr_adapted(I, Im, x): #ADAPTED: In order to determine the gradient of the parameters, you only #need the correlation value. So, the outputs: Th and Im_t are removed. #Nothing else is changed. #Attention this function will be used for ngradient in the function: #intensity_based_registration_rigid_adapted. # Computes normalized cross-corrleation between a fixed and # a moving image transformed with an affine transformation. # Input: # I - fixed image # Im - moving image # x - parameters of the rigid transform: the first element # is the roation angle, the second and third are the # scaling parameters, the fourth and fifth are the # shearing parameters and the remaining two elements # are the translation # Output: # C - normalized cross-corrleation between I and T(Im) # Im_t - transformed moving image T(Im) NUM_BINS = 64 SCALING = 100 #------------------------------------------------------------------# # TODO: Implement the missing functionality T_rotate = reg.rotate(x[0]) #make rotation matrix (2x2 matrix) T_scaled = reg.scale(x[1], x[2]) #make scale matrix (2x2 matrix) T_shear = reg.shear(x[3], x[4]) # make shear matrix (2x2 matrix) t = np.array(x[5:]) * SCALING #scale translation vector T_total = T_shear.dot( (T_scaled).dot(T_rotate) ) #multiply the matrices to get the transformation matrix (2x2) Th = util.t2h( T_total, t) #convert to homogeneous transformation matrix (3x3 matrix) Im_t, Xt = reg.image_transform(Im, Th) #apply transformation to moving image C = reg.correlation( Im, Im_t ) #determine the correlation between the moving and transformed moving image #------------------------------------------------------------------# return C
# assigning space [ cor_pbr, cor_pbr2, cor_cc_rig, cor_cc_rig2, cor_cc_af, cor_cc_af2, cor_mi, cor_mi2 ] = [np.zeros(len(t1)) for i in range(8)] [MI_pbr, MI_pbr2, MI_cc_rig, MI_cc_rig2, MI_cc_af, MI_cc_af2, MI_mi, MI_mi2] = [np.zeros(len(t1)) for i in range(8)] countimages = len(t1) # executing registration and saving coralation and mutual information for i in range(countimages): I, Im, It = pbr.pbr(r'..\data\image_data\\' + t1[i], r'..\data\image_data\\' + t1d[i]) cor_pbr[i] = reg.correlation(I, It) MI_pbr[i] = reg.mutual_information(reg.joint_histogram(I, It)) for i in range(countimages): I, Im, It = pbr.pbr(r'..\data\image_data\\' + t1[i], r'..\data\image_data\\' + t2[i]) cor_pbr2[i] = reg.correlation(I, It) MI_pbr2[i] = reg.mutual_information(reg.joint_histogram(I, It)) print('Point-based: done') # t1 to t1 for i in range(countimages): sim1, I_cc_rig, Im_cc_rig = proj.intensity_based_registration( r'..\data\image_data\\' + t1[i], r'..\data\image_data\\' + t1d[i], 0, 0, 0) cor_cc_rig[i] = sim1[-1]