MATLAB: Number of Object in binary image

binarybinary imagedigital image processingimage analysisimage processingImage Processing Toolboximage segmentationnumber of objectsobject count in binary image

Hi, im trying to get the number of objects in an binary image but it return the wrong answer (it should be 6 but it return 31). here is the code and the image:
I=imread('2.jpg');
I_BW=im2bw(I,0.87);
I1=imcomplement(I_BW);
[L,n]=bwlabel(I1);
bw.PNG

Best Answer

Try this:
bw = imread('bw.png');
if ndims(bw) > 1
bw = bw(:,:,1);
end
% Threshold
bw = bw > 128;
subplot(1, 2, 1);
imshow(bw, []);
% Fill holes
bw = imfill(bw, 'holes');
% Get areas
props = regionprops(bw, 'Area');
sortedAreas = sort([props.Area], 'descend')
% Looks like we need to throw away any blobs less than 1000 pixels or so
bw = bwareaopen(bw, 1000);
subplot(1, 2, 2);
imshow(bw);
% Count the blobs
[labeledImage, numBlobs] = bwlabel(bw);
fprintf('Found %d shapes.\n', numBlobs);