MATLAB: Image Registration Issues – imregister() is making the moving image more misaligned

image analysisimage processingImage Processing ToolboxMATLAB

Hi, I posted this question earlier and had a mistake in the code, so I'm posting it again here:
I'm a beginner in MATLAB, trying to align some images using imregister(). The images are of biological tissue sections. I am having some major issues aligning the images… the result from imregister() flips the image upside down, when it shouldn't be.
Why would imregister() flip the moving image upside down like this? The resulting image is now even more mis-aligned to the fixed imaged than it was pre-registration. Also, the tissue sections to be aligned in the fixed and moving images are very similar to begin with so I'm not sure why imregister() would make such a false alignment.
Here is my very basic code:
fixed = imread('slice2.jpg');
moving = imread('slice3.jpg');
gfixed = rgb2gray(fixed);
gfixed2 = medfilt2(gfixed);
img1 = adapthisteq(gfixed2);
gmoving = rgb2gray(moving);
gmoving2 = medfilt2(gmoving);
img2 = adapthisteq(gmoving2);
[optimizer,metric]=imregconfig('monomodal');
optimizer.GradientMagnitudeTolerance = 1.00000e-04;
optimizer.MinimumStepLength = 3.00000e-04;
optimizer.MaximumStepLength = 6.25000e-02;
optimizer.MaximumIterations = 300;
optimizer.RelaxationFactor = 0.500000;
im_aligned = imregister(img2, img1,'rigid',optimizer,metric);
figure(1),imshowpair(img1,im_aligned); % shows im_aligned is flipped sideways
Please note that I have a large stack of images that I need to apply this code to, so the same issue shown here is happening with other pairs of images in the stack as well. I'm hoping someone can tell me why this is generally happening so I can work at achieving a decent alignment.

Best Answer

I got better results with a multimodal registration. Also, masking out the background junk is a good idea.
load Masks %Use the attached .mat file.
[optimizer,metric]=imregconfig('multimodal');
imrf=imref2d(size(img1));
tform = imregtform(double(img2).*mask2, imrf, double(img1).*mask1, imrf, 'rigid',optimizer,metric);
im_aligned=imwarp(img2,tform,'OutputView',imrf);
figure(1),imshowpair(img1,im_aligned);