MATLAB: Image registration fucntions don’t work for a simple test

alignmentimage processingImage Processing Toolboxregistrationtranslation

I am trying to use MATLAB to do image registration that is based on translation only, so I did a simple test first.
First, I created 2 simple binary images:
You can see there is a 20-pixel shift in the vertical direction between those 2 images, then I tried 2 functions to do the registration:
[optimizer,metric] = imregconfig('Monomodal');
tform = imregtform(img1,img2,'Translation',optimizer,metric);
img1reg = imregister(img1,img2,'Translation',optimizer,metric);
Neither "imregtform" nor "imregister" worked; "imregtform" gave an identity transformation matrix, and the output of "imregister", "img1reg", was exactly same as the input moving image "img1".
How can I fix this?
Here is the code I used:
img1 = zeros(100, 20);
img1(35:45,:) = 1;
img2 = zeros(100, 20);
img2(55:65,:) = 1;
[optimizer,metric] = imregconfig('Monomodal');
tform = imregtform(img1,img2,'Translation',optimizer,metric);
img1reg = imregister(img1,img2,'Translation',optimizer,metric);

Best Answer

You need to consider smaller translations. With such a large translation, the object in the fixed image does not overlap the object in the moving image at all. Therefore, there is no gradient in the registration cost function with which to direct the algorithm.
Commonly, people will do a correlation-based registration first to capture gross misalignment like the above, and then refine.