Do you have any idea to find all connected components in a binary image in Matlab without bwlabel?

2 views (last 30 days)
I have been trying to create a code, but I couldn' t.My idea is an algorithm to find all connected componets using 8 neighbors in a binary image, without using the function "bwlabel". For example, my input matrix is:
a =
1 1 0 0 0 0 0
1 1 0 0 1 1 0
1 1 0 0 0 1 0
1 1 0 0 0 0 0
0 0 0 0 0 1 0
0 0 0 0 0 0 0
I would to have something like this:
a =
1 1 0 0 0 0 0
1 1 0 0 2 2 0
1 1 0 0 0 2 0
1 1 0 0 0 0 0
0 0 0 0 0 3 0
0 0 0 0 0 0 0
There are 3 connected objects in this image, please Help, anything would be appreciated!

Accepted Answer

Guillaume
Guillaume on 13 Oct 2014
It's not particularly hard to implement.
Go over each pixel starting in the upper left corner. You just scan your image top-to-bottom, left-to-right and check the left, top and top-left pixels of non-zero pixels. If those neighbours are 0, you assign a new value to your pixel, Otherwise you assign the value of those neighbours to your pixel.
The only tricky bit happens when the left and top pixel both have a value that differ. This means you need to merge them at a later stage, so just record somewhere (in a map for example) both values and assign one of them to your pixel.
Once you've assigned a value to each non-zero pixel, you go back over them to merge the numbers in your map.

More Answers (1)

Image Analyst
Image Analyst on 13 Oct 2014
Then use bwconncomp() instead, and ask for the labelMatrix property. No need to do it yourself mnaually.

Community Treasure Hunt

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

Start Hunting!