findcontours finds too many contours. [closed]
Is it normal that find contours finds so many contours where there are obviously only 3 contours ?
The code is :
Mat image;
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
image = imread(argv[1], 0); // Read the file
findContours(image, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
cout << contours.size();
RNG rng(12345);
Mat drawing = Mat::zeros(image.size(), CV_8UC3);
for (int i = 0; i< contours.size(); i++)
{
Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
drawContours(drawing, contours, i, color, 2, 8, hierarchy, 0, Point());
}
/// Show in a window
namedWindow("Contours", CV_WINDOW_AUTOSIZE);
imshow("Contours", drawing);
namedWindow("Display window", WINDOW_AUTOSIZE);// Create a window for display.
imshow("Display window", image); // Show our image inside it.
Use CV_RETR_EXTERNAL instead of CV_RETR_TREE, which retrieves only the extreme outer contours.
I found the problem. It wasn't using CV_RETR_TREE. findContours only works properly on "edge images". So you have to run canny first
@Dionysos, running canny first is kind of an overkill. Using the correct parameter solves it all. findContours wants binary images, of which edge images are a sort, but blobs is just fine if you use the external parameter.
Steve, that's what I thought but I was using a binary image (the top one). The bottom one is the contours drawn (where you see that there's too many).
the problem is here . you need to binarize the image.