I wanted to reproduce the example about connected components found here (the code is no longer online and I wanted to use the C++ API).
I have used the following call to findCountours
:
findContours(img, contours, hierarchy, CV_RETR_CCOMP,CV_CHAIN_APPROX_SIMPLE);
where img is obtained by thresholding the image proposed in the article:
input image http://img8.imageshack.us/img8/7249/78825396.png
The expected output is:
output image http://img8.imageshack.us/img8/5142/resultw.png
From the description of CV_RETR_CCOMP
I was expecting to have 6 top-levels contours which correspond to the 6 colors of the result image.
It said in the doc that the connected components are at the top-level and the holes are child of the connected components (CC).
However from the exploration of hierarchy
, I can see that the first 3 contours (0, 1, 3) have neither parent or child. They correspond to the holes in the 'a' letters. The other contours are in the hierarchy (see dump at the end). Contours 3 is the "top-level" CC that contain all the image. The other contours are the outer contours of the expected CC.
Contour 0: next: 1, previous: -1, child: -1, parent: -1, size: 4
Contour 1: next: 2, previous: 0, child: -1, parent: -1, size: 4
Contour 2: next: 3, previous: 1, child: -1, parent: -1, size: 4
Contour 3: next: -1, previous: 2, child: 4, parent: -1, size: 4
Contour 4: next: 5, previous: -1, child: -1, parent: 3, size: 121
Contour 5: next: 6, previous: 4, child: -1, parent: 3, size: 80
Contour 6: next: 7, previous: 5, child: -1, parent: 3, size: 18
Contour 7: next: 8, previous: 6, child: -1, parent: 3, size: 18
Contour 8: next: 9, previous: 7, child: -1, parent: 3, size: 18
Contour 9: next: -1, previous: 8, child: -1, parent: 3, size: 8
I have tested the code with OpenCV 2.2 and 2.3.1. I have tested with a simpler image (a circle with a hole) and got the same result (3 contours: 0 is the hole, 1 is the top-level, 2 is the outer contour).
Can somebody explain how this is related to the doc of CV_RETR_CCOMP
?