Get coordinates of contours in OpenCV

kav picture kav · May 13, 2015 · Viewed 17.1k times · Source

Let's say that I have the following output image:

enter image description here

Basically, I have video stream and I want to get coordinates of rectangle only in the output image. Here's my C++ code:

while(1)
    {
        capture >> frame;

        if(frame.empty())
            break;

        cv::cvtColor( frame, gray, CV_BGR2GRAY ); // Grayscale image

        Canny( gray, canny_output, thresh, thresh * 2, 3 );

        // Find contours
        findContours( canny_output, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );

        // Draw contours
        Mat drawing = Mat::zeros( canny_output.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() );
        }

        cv::imshow( "w", drawing );

        waitKey(20); // waits to display frame

    }

Thanks.

Answer

Aristu picture Aristu · May 13, 2015

Look at the definition of the find contours function in the opencv documentation and see the parameters (link):

void findContours(InputOutputArray image, OutputArrayOfArrays contours, OutputArray hierarchy, int mode, int method, Point offset=Point())

Parameters: here

Look at contours, like Rafa said each contour is stored in a vector of points and each vector of points is stored in a vector, so, by walking in the outer vector and then walking in the inner vector you'll be finding the points you wish.

However, if you want to detect only the bigger contour you might want to use CV_RETR_EXTERNAL as the mode parameter, because it'll detect only most external contour (the big rectangle).

If you still wish to maintain the smaller contours then you might use the CV_RETR_TREE and work out with the hierarchy structure: Using hierarchy contours