1 | initial version |
Because the OpenCV connected components algorithm is designed for binary input, it will not find the holes which you have labeled 0(b) and 0(c).
My suggestion is to perform Canny edge detection (or any edge detection, since your image is simple enough), followed by bitwise negation, and finally the connected components labeling with connectivity = 4.
Here are some explanations of the detail I gave above.
The bitwise negation causes the "Canny edge pixels" to become background pixels. In other words, they are delimiters - they represent pixels that do not connect, thus segmenting distinctly colored regions into pieces. All remaining pixels become foreground pixels.
The connectivity needs to be 4 because the pixel chains formed by Canny are 8-connected. That is, sometimes the edge pixels go in diagonal directions. If the connected component algorithm had used 8-connectivity, it would leak through the boundary formed by the edge pixel chains. Using 4-connectivity in the connected component algorithm will not have this problem.