MATLAB: How to use IMTRANSFORM function with a grid overlay for projective transformation of the image

Image Processing Toolboximtransformprojective

I would like to use the IMTRANSFORM function to perform a projective transformation of my image with a grid overlay.

Best Answer

In this example of using the IMTRANSFORM with 'projective' option and a grid overlay, we have defined 4 control points which we want to map onto some base points that form the vertices of a rectangle.
Note that the result is fuzzy because of the resampling; therefore you will not see a single white pixel at each of the four bright points in the zOut image.
% I want to map control_points to base_points
control_points = [ 3,3 ; 2,8 ; 8,3 ; 9,8 ]
base_points = [ 3,3 ; 3,8 ; 8,3 ; 8,8 ]
% make control points white
zIn = zeros(10,10,'uint8');
for k =1:size(control_points,1)
zIn(control_points(k,2),control_points(k,1)) = intmax('uint8');
end
iptsetpref('ImshowInitialMagnification','fit')
iptsetpref('ImshowAxesVisible','on')
% calculate transformation from control points
tform = cp2tform(control_points,base_points,'projective');
[zOut,x,y] = imtransform(zIn,tform,'bicubic');
% Calculate grids to overlay on images
[X,Y] = meshgrid(1:9,1:9);
[U,V] = tforminv(tform,X,Y);
% Create shade of gray
gray = 0.65 * [1 1 1];
% plot original image
figure, imshow(zIn)
hold on
line(U, V, 'Color',gray);
line(U',V','Color',gray);
% plot output
figure, imshow(zOut,'XData',x,'YData',y)
hold on
line(X, Y, 'Color',gray);
line(X',Y','Color',gray);