I am trying to make sense of the hierarchy in the findContour
function in OpenCV. I am using RETR_CCOMP
to hopefully find the parent contours and whether or not they have 'children'. My find contour hierarchy vector seems to suggest there are far more parent contours then are visible in the output which makes it more difficult to use.
Is it possible to get around this problem?.
Here's my code:
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace cv;
using namespace std;
Mat src;
Mat src_gray;
Mat src_edges;
int main(int argc, char** argv)
{
src = imread("image.jpg", CV_LOAD_IMAGE_UNCHANGED);
cvtColor(src, src_gray, CV_BGR2GRAY);
blur(src_gray, src_gray, Size(3, 3));
Canny(src_gray, src_edges, 200, 120);
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
findContours(src_edges, contours, hierarchy, RETR_CCOMP, CV_CHAIN_APPROX_TC89_L1, Point(0, 0));
for (auto vec : hierarchy)
std::cout << vec << std::endl; // just to have a look at the hierarchy vector
int count = 0;
for (int i = 0; i < 5; i++){
if (hierarchy[i][3] != 0){
count++;
}
}
cout << "number of labels = " << count << endl;
Mat drawing = Mat::zeros(src_gray.size(), CV_8UC3);
for (int i = 0; i < contours.size(); i++)
{
Scalar color = Scalar(rand() & 255, rand() & 255, rand() & 255);;
drawContours(drawing, contours, i, color, 2, 8, hierarchy, 0, Point());
}
namedWindow("Contours", CV_WINDOW_AUTOSIZE);
imshow("Contours", drawing);
namedWindow("Original Image", CV_WINDOW_AUTOSIZE);
imshow("Original Image", src);
waitKey(0);
return(0);
}
Here an example image: