1

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?

Mathieu Dubois
  • 1,054
  • 3
  • 14
  • 22
  • My question is close to [this one](http://stackoverflow.com/questions/8461612/using-hierarchy-in-findcontours-in-opencv) (see the comment of SSteve). – Mathieu Dubois Dec 05 '12 at 08:08
  • Well, the output of `CV_RETR_TREE` seems closer to the desired output. The first contour is the global contour, it's children are the outer contours of the CC. The child of those contours are the holes. However it does not handle correctly CC inside holes. – Mathieu Dubois Dec 05 '12 at 10:06
  • OK, I Understood my problem... I was misguided by the visual appearance of the input. For `findContours()` pixels' object must be at `255` (appear white) and holes at `0` (appear black). So I need to use the negation of the input image. – Mathieu Dubois Dec 11 '12 at 22:42

0 Answers0