MATLAB: How to get displacement field from tform

displacement fieldImage Processing Toolboximage registrationtform

I would like to represent a rigid image transformation (tform) that I have determined as a displacement field, (D).
In the code below I try to make such a displacement field (D) from tform, but when I use tform and D on the same image I get two different results. If someone can spot what I am doing wrong when I make the displacement field I would be very grateful. Or alternatively know of another way to get the displacement field from tform…
% import matlab standard images
fixed = imread('hands1.jpg');
moving = imread('hands2.jpg');
fixed = rgb2gray(fixed);
moving = rgb2gray(moving);
% determine a rigid tform
[optimizer, metric] = imregconfig('monomodal');
tform = imregtform(moving, fixed, 'rigid', optimizer, metric);
% use found tform to warp moving image
moving_reg1 = imwarp(moving,tform);
% make a displacement field that corresponds to tform
[X,Y] = meshgrid(1:size(moving,2),1:size(moving,1)); % make grids with x and y coordinates of pixels
[XT,YT] = transformPointsForward(tform,X,Y); % Transform pixel coordinates using tform
D = zeros(size(X,1),size(X,2),2);
D(:,:,1) = X-XT; % displacement field should be the difference!?
D(:,:,2) = Y-YT;
moving_reg2 = imwarp(moving,D); % warp moving image with the new displacement field
% now I would expect the two registered images moving-reg1 and moving-reg2
% to be the same - but they are not!
figure
imshowpair(moving_reg1,moving_reg2); title('moving-reg1 and moving-reg2')

Best Answer

Hi Silja,
The issue is because you are using an incomplete syntax of 'imwarp' in the code. 'imwarp' function has an 'OutputView' parameter to preserve world limits and resolution of the fixed image when forming the transformed image.
Use the following line of code instead of 'moving_reg1 = imwarp(moving,tform);'
moving_reg1 = imwarp(moving,tform,'OutputView',imref2d(size(fixed)));