%% Exercise "Rectifying and referencing images using imwarp"
%
% by Martin H. Trauth, 2 May 2017
% http://mres.uni-potsdam.de
clear, close all, clc

%%
% Load image
I1 = imread('IMG_8813.JPG');

%%
% Display image
imshow(I1)

%%
% Define coordinate system
inputpoints(1,:) = [0 0];
inputpoints(2,:) = [0 131];
inputpoints(3,:) = [656 0];
inputpoints(4,:) = [656 131];

%%
% Pick pixel xy from image: upperleft, lowerleft, upperright, lowerright,
% then return
basepoints = ginput;

%%
% Image transformation
tform = fitgeotrans(basepoints,inputpoints,'projective');

%%
xLimitsIn = 0.5 + [0 size(I1,2)];
yLimitsIn = 0.5 + [0 size(I1,1)];

%%
[x,y] = outputLimits(tform,xLimitsIn,yLimitsIn);

%%
Rout = imref2d(size(I1),x,y);

%%
I2 = imwarp(I1,tform,'OutputView',Rout);

%%
close all
figure('Position',[50 500 1200 600])
axes('YDir','reverse',...
    'XLim',[x(1) x(2)],...
    'YLim',[y(1) y(2)],...
    'FontSize',18), hold on
xlabel('Width (cm)',...
    'FontSize',18)
ylabel('Height (cm)',...
    'FontSize',18)
image(I2,'XData',x,'YData',y)

axes('YDir','reverse',...
    'XLim',[x(1) x(2)],...
    'YLim',[y(1) y(2)],...
    'XGrid','on',...
    'YGrid','on',...
    'Color','none',...
    'XTickLabels',[],...
    'YTickLabels',[])

%%
print -dpng -r300 rectifiedimage_vs1.png




