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

image processingImage Processing Toolboxmorphological operations

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!

Best Answer

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.
Related Question