findcontours finds too many contours. [closed]

asked 2015-01-31 09:35:57 -0600

Dionysos gravatar image

Is it normal that find contours finds so many contours where there are obviously only 3 contours ? image description

image description

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.
edit retag flag offensive reopen merge delete

Closed for the following reason the question is answered, right answer was accepted by sturkmen
close date 2020-10-10 14:19:16.450046

Comments

1

Use CV_RETR_EXTERNAL instead of CV_RETR_TREE, which retrieves only the extreme outer contours.

Haris gravatar imageHaris ( 2015-01-31 10:08:13 -0600 )edit
1

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 gravatar imageDionysos ( 2015-01-31 14:13:10 -0600 )edit
1

@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.

StevenPuttemans gravatar imageStevenPuttemans ( 2015-02-01 02:21:51 -0600 )edit

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).

Dionysos gravatar imageDionysos ( 2015-02-01 09:02:46 -0600 )edit

the problem is here . you need to binarize the image.

image = imread(argv[1], 0);   // Read the file
findContours(image, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
sturkmen gravatar imagesturkmen ( 2020-10-10 14:18:21 -0600 )edit