The function bwlabel
from the image processing toolbox is the ideal function you should use to label each continuous region of non-zero pixels in a binary mask. However, you want to perform this on the zero pixels that are delineated by the "boundary" pixels that are set to 1. Therefore, simply use the inverse of the binary mask so that you are operating on the zero pixels instead of the non-zero pixels. Also from your definition, regions are separated using a 4 pixel connectivity. bwlabel
by default uses 8 pixel connectivity when searching for continuous regions, which means that it looks in the N, NE, E, SE, S, SW, W and NW directions. You'll want to manually specify 4 pixel connectivity, which looks in only the directions of N, E, S and W.
Supposing your mask was stored in the variable L
, simply do:
labels = bwlabel(~L, 4);
The output labels
would be a map that tells you the membership of each pixel. Regions of the same membership tells you that those pixels belong to the same group.
Using your example, we get:
>> L = [0 0 0 1 0 0 0 1 0 0
0 0 1 0 0 0 0 1 0 0
1 1 0 1 0 0 0 1 0 0
0 0 0 0 1 0 1 0 0 0];
>> labels = bwlabel(~L, 4)
labels =
1 1 1 0 3 3 3 0 4 4
1 1 0 3 3 3 3 0 4 4
0 0 2 0 3 3 3 0 4 4
2 2 2 2 0 3 0 4 4 4
Each island of zeroes has a unique ID where pixels that belong to same ID belong to the same island or region. If you don't want to use bwlabel
and do this from first principles, you can refer to my previous post using Depth First Search to find regions of connected components: How to find all connected components in a binary image in Matlab?. Be advised that this is not efficient code and so you should only use it for educational and research purposes. Using bwlabel
is recommended as it is a fast function and well tested. You'll also have to modify the code so that it doesn't search in an 8 pixel connectivity and it should look at only a 4 pixel connectivity. Make sure you also inverse the input before using the code.