This post is about labeling the connected components
in a binary image and crop the connected components based on the
label. The main two functions used for this simple operation are ‘bwlabel’ and ‘regionprops’.
I used ‘bwlabel’ to label
the connected components. After labeling,
I used ‘regionprops’ function to find the rectangle containing the region. To find the rectangle points, I used ‘BoundingBox’
property.
Then the labeled components are
automatically cropped and the image is displayed. To crop an image, ‘imcrop’
function is used.
MATLAB CODE:
A=imread('coins.png');
figure,imshow(A); title('Original Image');
%Convert the Image to binary
B=im2bw(A);
%Fill the holes
C=imfill(B,'holes');
%Label the connected components
[Label,Total]=bwlabel(C,8);
figure,imshow(C); title('Labelled Image');
%Rectangle containing the region
Sdata=regionprops(Label,'BoundingBox');
%Crop all the Coins
for i=1:Total
Img=imcrop(A,Sdata(i).BoundingBox);
Name=strcat('Object Number:',num2str(i));
figure,imshow(Img); title(Name);
end