Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

How can i compare 2d shapes in mat lab?

Asked by Angus on 18 Jul 2013

I'm trying to use MATLAB 2013 on windows for a science project to compare various 2d white shapes on a black background.

I need to know how many white pixels overlap between two images.

I have no idea how to create an algorithm to do this.

Please help me!




1 Answer

Answer by Evan on 18 Jul 2013
Edited by Evan on 18 Jul 2013
Accepted answer

In the below example, I'm assuming that you're going to be working with RGB data. That is, I'm assuming that your images aren't already grayscale or black and white images when you load them in. If they're already grayscale or BW, skip the second or second and third steps respectively:

First, load in your image:

rgb_img1 = imread(filePath1); %filePath is the full path where your image file is located

Next, convert to grayscale:

gry_img1 = rgb2gray(rgb_img1);

Next, threshold your image to find the "white spots" in the image and get a black and white (1s and 0s) image. The value is something you'll have to determine based on the brightness of your shapes compared to the background. Here, I'm choosing 0.9.

bin_img1 = gry_img1 > 0.9;

Then, perform the same steps for your second image:

rgb_img2 = imread(filePath2);
gry_img2 = rgb2gray(rgb_img2);
bin_img2 = gry_img2 > 0.9;

Finally, compare your images. Anywhere where both binary images return "true" is a pixel where they overlap.

 overlap = bin_img1 & bin_img2;

Now, what you do with this data (i.e. how you visualize it) is up to you. For example, you could plot the rgb or grayscale images where overlap occurs, or you could overlay one binary image on the other.

Finally, the user Image Analyst has a few tutorials on the file exchange that you might find helpful for getting started on basic image processing:


Angus on 18 Jul 2013

2) I mean a volume with (x,y,z,) coordinates on a 3 dimensional array.

Evan on 18 Jul 2013

Hmm. Since that one seems to be less about image processing and more about finding overlap of 3D shapes made of discrete points, I would say you would probably get better feedback if you pose it as a separate question here (plus, it'll keep things organized so other users will be able to search for your question if they're trying to do the same thing). So, unless you have further questions regarding image overlap or the above answer didn't resolve your problem, you could accept this answer and start a new thread.

Angus on 19 Jul 2013


Thanks again for your help.


Contact us