Clear Filters
Clear Filters

bwlabel changes the number of pixels in blobs

1 view (last 30 days)
Hey
I have a logical image containing 3 components as seen here:
I then use the bwlabel function on the image and get the following image:
I do not understand why bwlabel adds pixels to one of the components. I use bwlabel with the default settings.

Accepted Answer

Image Analyst
Image Analyst on 14 Sep 2023
Your image is not a binary image. It's an RGB image. bwlabel returns a labeled image as a double, not a binary image as you showed in your second image. So I have no idea what your original image really was and what code you used to produce the labeled image. This is what I did:
rgbImage = imread('bwlabel.png');
class(rgbImage)
ans = 'uint8'
size(rgbImage)
ans = 1×3
496 852 3
subplot(2, 2, 1);
imshow(rgbImage, []);
title('Original RGB Image')
axis('on', 'image');
impixelinfo
if size(rgbImage, 3) == 3
fprintf('Converting RGB image to logical/binary image.\n')
rgbImage = logical(rgbImage(:, :, 2));
subplot(2, 2, 2);
imshow(rgbImage, []);
title('Now converted to gray scale Image')
impixelinfo
axis('on', 'image');
end
Converting RGB image to logical/binary image.
% Crop off the frame with a gray level of 240.
rgbImage = rgbImage(9:478, 13:834);
% Label the image.
[labeledImage, numBlobs] = bwlabel(rgbImage);
class(labeledImage)
ans = 'double'
fprintf('Found %d blobs in the binary image', numBlobs);
Found 3 blobs in the binary image
subplot(2, 2, 3);
imshow(labeledImage, []);
impixelinfo
title('Labeled RGB Image')
axis('on', 'image');
As you can see from my code above, the labeled image has no more non-zero pixels than your original image.
  1 Comment
DGM
DGM on 14 Sep 2023
I think it's important to note where exactly the distinction is occurring. When calling bwlabel() with any image that's not logical-class, it will be cast as logical before labeling. This is equivalent to
bw = bw ~= 0;
... which is rarely a good threshold value if you're trying to binarize an image.
The lesson? Make sure your image is satisfactorily binarized before feeding it to bwlabel(), bwconncomp(), etc. Otherwise, bwlabel() will make it binary with complete disregard for the content.

Sign in to comment.

More Answers (0)

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!