How to count pixels overlapping between two images?

2 次查看(过去 30 天)
Dear MatLab community,
I'm looking for a script in order to count the number of pixels overlapping between two images.
I've been trying to write it by myself, after a while it is still not working...
Could someone help me with that ?
Here are two images (for instance) that I would like to compare (I need to do it for multiple images).
Thank you in advance !
  1 个评论
DGM
DGM 2025-4-9
How many pixels overlap between two dissimilarly-sized RGBA images with zero color content? That's a question for you to answer.
The images have no object content in the color layers. They are entirely, purely black. Zero. If we consider color content, is that 0% overlap, or 100% overlap? This is the color content of both images:
Even if we consider the alpha content, are you looking for the overlap between the numbers or the background? The alpha content represents the numbers as the foreground. When composed with white, the composite image represents the numbers as the background. Which is intended?
What exactly constitutes "overlap"? Is it the intersection of two somehow binarized representations of the images, or is it just the minimum of their dissimilar image geometries?
If they're to be binarized and compared, what is the spatial relationship between the two images? Should they be scaled to fit, cropped, or both? If they're to be scaled, should one be scaled up, or the other scaled down? What if the images have dissimilar aspect ratios? Should the characters be deformed? If cropped, where should they be aligned? Should the characters be aligned based on font geometry instead of their position in the image? Is there a limit to how much the sizes vary in the set?
How would you align these two images? Would it produce anything meaningful to compare two stretched-out characters?
Like this? ... or this?
Some of these might sound like facetious doubts, but once the more obvious ambiguities start being ignored, it's worth questioning whether anything is being considered.

请先登录,再进行评论。

回答(1 个)

Vedant Shah
Vedant Shah 2025-4-9
Firstly, we can read the images using the `imread` function as shown below:
image1 = imread(image1.png');
image2 = imread(image2.png');
Next, we need to convert the images to grayscale and then convert them to binary, as shown below:
gray1 = im2gray(image1);
gray2 = im2gray(image2);
bw1 = imbinarize(gray1);
bw2 = imbinarize(gray2);
Then, we will resize the images to ensure they are of the same size:
[rows, cols] = size(bw1);
bw2 = imresize(bw2, [rows, cols]);
Finally, we can find the number of overlapping pixels as desired.
overlap = bw1 & bw2;
numOverlapPixels = sum(overlap(:));
For more information refer to the following documentation:

Community Treasure Hunt

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

Start Hunting!

Translated by