incorrect results from bwconncomp
14 views (last 30 days)
Show older comments
Erin Linebarger
on 14 Feb 2019
Commented: Image Analyst
on 16 Feb 2019
I would like to understand how to correctly use the bwconncomp function, as the results I get do not make sense. Here is my problem. I have a binary image of edges like so:

It has been preprocessed to remove all vertices. I want to identify all the edges individually, so I ran the code:
CC1 = bwconncomp(E1);
It says there are only 13 objects, which looks highly suspect, so I pull up the first object like this:
%create cell array of edge matrices
numPixels1 = length(CC1.PixelIdxList);
edges1 = cell(num_1,1);
for ii = 1:num_1
pix = CC1.PixelIdxList{ii};
[rows,cols] = ind2sub(size(E1),pix);
r = max(rows)-min(rows)+1;
c = max(cols)-min(cols)+1;
mat = zeros(r,c);
rows = rows - min(rows)+1;
cols = cols - min(cols)+1;
inds = sub2ind([r,c],rows,cols);
mat(inds) = 1;
edges1{ii} = mat;
end
%show first element
figure;imshow(edges1{1})
And I get this:

I don't understand how counting connected components would actually connect those components before counting, it seems precisely in oppposition to the goal. Please help to clarify the use of this function.
3 Comments
Accepted Answer
Image Analyst
on 16 Feb 2019
Identify the branchpoints with bwmorph() then mask them out.
bpImage = bwmorph(mask, 'branchpoints'); % Find branchpoints in your binary image called "mask"
mask(bpImage) = false; % Erase those branchpoints.
2 Comments
Image Analyst
on 16 Feb 2019
Yes, while logical variables CAN be treated as numbers 0 and 1, it's always best to use logical operations to avoid the problem you saw. Subtracting a true (1) from a false (0) will require them to be cast to double instead of logical so it can handle the -1. Then that causes weird side effects like you saw, along with not being able to use the array as a logical index anymore (like I did). So while in some circumstances you can use mathemetical operations, it's always safest to stick with logical operations when dealing with logical variables.
Thanks for accepting the answer.
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!