Reputation: 85
Given a BW image that contains some connected components. Then, given a single pixel P in the image. How to find which component that contains the pixel P? It is guaranteed that the pixel P is always on the white area in one of the connected components.
Currently, I use CC = bwconncomp(BW) than I iterate each component using 'for' loop. In the each component, I iterate the index pixel. For each pixels, I check whether the value equal to the (index of) pixel P or not. If I find it, I record the number of connected component.
However, it seems it is not efficient for this simple task. Any suggestion for improvement? Thank you very much in advance.
Upvotes: 0
Views: 1004
Reputation: 6162
MATLAB provides multiple functions that implement connected-component in different ways.
In your example, I would suggest bwlabel
.
http://www.mathworks.com/help/images/ref/bwlabel.html
[L, num] = bwlabel(imgBW)
This will perform a full-image connected-component labeling on a black-and-white image.
After calling this function, the label value that pixel P belongs to can be read off the result matrix L
, as in label_to_find = L(row, col)
index. Simple as that.
To extract a mask image for that label, use logical(L == label_to_find)
.
If you use different software packages such as OpenCV you will be able to get better performance (efficiency in terms of cutting unnecessary or redundant computation), but in MATLAB the emphasis is on convenience and prototyping speed.
Upvotes: 1