How do I compare two images on matlab?

19 views (last 30 days)
J W
J W on 30 Mar 2021
Edited: Adam Danz on 1 Apr 2021
Hi, I'm quite new to matlab hence I am asking this as I have been stuck after searching the entire day. I have two image files, let's call them A and B (both greyscale). B is the exact same thing as A but the region of interest is shifted vertically downwards by a number of pixels. I am trying to find that number of pixels. I don't have a source code for it currently as I am completely stuck and need some help for it. My idea is to change the image pixels into a matrix and try to compare them somehow.
Many thanks for the help!
  2 Comments
Adam Danz
Adam Danz on 30 Mar 2021
If the images are exactly the same except for one region, can't you just read in both images and compare their numeric matrices to find where they differ? Maybe it's not as simple as that in which case we need more info.
J W
J W on 30 Mar 2021
Edited: J W on 30 Mar 2021
Yes, that was what I was thinking about. But how do I compare the matrices? How do I compare them row by row?

Sign in to comment.

Answers (1)

Adam Danz
Adam Danz on 31 Mar 2021
Edited: Adam Danz on 1 Apr 2021
> B is the exact same thing as A but the region of interest is shifted vertically downwards by a number of pixels. I am trying to find that number of pixels.
It would be easier if we had a simple image for an example but let's use this one, hoping that its similar to your goal.
Notice that these two images are exactly alike except for the vertical shift of a 3x3 area.
  1. Read in both images. You could use imread.
  2. Using the numeric representations of the images, perform a 2D cross correlation to compute the vertical and horizontal offsets.
Assuming the image on the left is A and the image on the right is B,
xc = xcorr2(A,B);
[~, maxIdx] = max(abs(xc(:)));
[rowMax, colMax] = ind2sub(size(xc),maxIdx);
offset = [(rowMax-size(B,1)) (colMax-size(B,2))] % <--- [vert,horz] offset from A to B
offset =
-2 0
This shows a vertical and horizontal offsets from A to B of 2 units and a horizontal offset of 0 units.
See another example in the documentation: Recovery of Template Shift with Cross-Correlation.
  1 Comment
Adam Danz
Adam Danz on 31 Mar 2021
Note to self: full code to generate the images:
rng('default')
A = rand(10,10)*10;
B = A;
patch = rand(3,3)*50;
A(3:5, 2:4) = patch;
B(5:7, 2:4) = patch;
figure()
subplot(1,2,1)
imagesc(A)
axis equal; axis tight; axis off
title('A')
subplot(1,2,2)
imagesc(B)
axis equal; axis tight; axis off
title('B')
% do 2D cross correlation
xc = xcorr2(A,B);
[~, maxIdx] = max(abs(xc(:)));
[rowMax, colMax] = ind2sub(size(xc),maxIdx);
offset = [(rowMax-size(B,1)) (colMax-size(B,2))]; % <--- [vert,horz] offset from A to B

Sign in to comment.

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!