%% Image registration
% This is useful anytime you have > 1 image, and you want to ensure that
% all the features in each frame are aligned.  We'll start by loading in
% two images
clear 
close all

img1 = im2double(imread('westconcordorthophoto.png'));
img2 = im2double(imread('westconcordaerial.png'));

figure
subplot(1,2,1)
imshow(img1)
subplot(1,2,2)
imshow(img2)

% The easiest way to register these two images is for the user to select
% concordant points in each image.

cpselect(img2,img1);

% The correlation points are saved as a variables
fixedPoints
movingPoints

% Now we want to define a mathematical transformation that will put image 1
% onto image2

transform = fitgeotrans(movingPoints, fixedPoints, 'projective');

% Note, you can have different types of alignments depending on the images.
% Affine = All Linear transformations, translation-mag-shear-rotaion
% similarity = rotation, mag, translation
% Projective = each dimension can be changed indpenedently

% Now we just have to modify the second image onto the first.

imgReg = imwarp(img2,transform);

figure
imshowpair(img1,imgReg,'blend')


% We can try other transforms as well

transform2 = fitgeotrans(movingPoints, fixedPoints, 'affine');
imgReg2 = imwarp(img2,transform2);
transform3 = fitgeotrans(movingPoints, fixedPoints, 'Similarity');
imgReg3 = imwarp(img2,transform3);

figure
imshowpair(img1,imgReg2,'blend')


figure
imshowpair(img1,imgReg3,'blend')

%% We can also have matlab do attempt to find a transform for us
clear
close all

img1 = im2double(imread('westconcordorthophoto.png'));
img2 = rgb2gray(im2double(imread('westconcordaerial.png')));

% imregconfig starts variables that we will use to align the images.  If
% the images are taken on the same system, choose monomodal, if they are
% different devices, multimodal.
[optimizer, metric] = imregconfig('monomodal');

% Use the imregister command to align the two images.  The arguments are
% the moving image, the fixed image, the type of transform, and the
% optimizer and metric generated from above.
newImg = imregister(img1,img2,'similarity',optimizer,metric);

figure
imshowpair(newImg,img2)


%% Time cost of different registration transforms
% A convienent function is the tic/toc.  It tells you how much has time has
% gone by between the tic and toc.

tic
pause(1)
toc

% We can use this to time how long it takes matlab to try the different
% registration transforms.
rigidTic = tic;
newImg1 = imregister(img1,img2,'rigid',optimizer,metric);
disp(['Time to complete rigid registration: ']);
toc(rigidTic)
figure
imshowpair(newImg1,img2)

similarityTic = tic;
newImg2 = imregister(img1,img2,'similarity',optimizer,metric);
disp(['Time to complete similarity registration: ']);
toc(similarityTic)
figure
imshowpair(newImg2,img2)



