find common elements of two binary images and remove rest in matlab

To find the common elements of two binary images, you can use the logical AND operation. This will give you a new binary image with elements that are 1 if and only if the corresponding elements of the original images were both 1. Here's an example:

main.m
%load binary images from file or create binary images
img1 = imread('image1.png');
img2 = imread('image2.png');

% convert the images to binary
img1 = imbinarize(img1);
img2 = imbinarize(img2);

% perform logical AND operation to find common elements
commonElements = img1 & img2;

% remove non-common elements from the original images
img1(~commonElements) = 0;
img2(~commonElements) = 0;

% display the results
subplot(1,3,1),imshow(img1),title('Image 1');
subplot(1,3,2),imshow(img2),title('Image 2');
subplot(1,3,3),imshow(commonElements),title('Common Elements');
569 chars
20 lines

In this code, we first load the two binary images and convert them to logical arrays using the imbinarize function. We then apply the logical AND operation to obtain a new binary image that contains only the common elements of the two input images.

Finally, we use the logical indexing feature of MATLAB to remove the non-common elements from the original images. We display the original images and the common elements using a subplot.

gistlibby LogSnag