Ask Your Question
2

How to draw an open (non-closed) contour using drawContours?

asked 2012-12-28 09:42:30 -0500

cyril gravatar image

updated 2020-11-15 02:09:14 -0500

Hi

I try to draw an open contour (as std::vector<cv::Point>) with drawContour but it always closes the contour itself...

Here's a short sample app:

#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>

int main(int argc, char *argv[])
{
    std::vector<std::vector<cv::Point> > contour;
    contour.push_back(std::vector<cv::Point>());

    contour[0].push_back(cv::Point(10, 80));
    contour[0].push_back(cv::Point(80, 90));
    contour[0].push_back(cv::Point(50, 10));

    cv::Mat imgContour(cv::Size(100, 100), CV_8UC3);

    // this should now draw 3 connected points -> 2 lines in between.
    // but it draws a closed polygon over the 3 points??
    cv::drawContours(imgContour, contour, 0, cv::Scalar(255,0,0), 1, 8);

    cv::imshow("Contour", imgContour);

    cv::waitKey(0);

    return 0;
}

I am working with Qt Creator 2.4.1 (Qt 4.7.4 32bit) and OpenCV 2.3.0 under Windows 7 SP1.

edit retag flag offensive close merge delete

2 answers

Sort by ยป oldest newest most voted
2

answered 2012-12-28 12:03:32 -0500

updated 2012-12-28 12:05:37 -0500

You can use polylines or draw contour by lines.

int main( int argc, char** argv )
{
    Mat img = imread("c:\\sample.bmp",0);
    vector<vector<Point> > contours;
    vector<Vec4i> hierarchy;
    imshow("org imgae",img);
    findContours( img, contours, hierarchy,CV_RETR_CCOMP, CV_CHAIN_APPROX_TC89_L1 );

    Mat newImg;
    img.copyTo(newImg);
    newImg.setTo(0);

    Scalar color( rand()&255, rand()&255, rand()&255 );

    for( size_t k = 0; k < contours.size(); k++ )
        approxPolyDP(Mat(contours[k]), contours[k], 3, true);

    cout << contours.size() << endl;
    for (size_t k=0;k < contours.size();k++)
        for (size_t i=1;i < contours[k].size();i++)
        cv::line(newImg, contours[k][i],contours[k][i-1],color,1);
        //cout << contours[k][i] << endl;


imshow("view",newImg);
waitKey(0);

    return 0;
}

image description

edit flag offensive delete link more
1

answered 2012-12-28 11:33:29 -0500

Michael Burdinov gravatar image

Use polylines function instead. It has flag that indicates whether the drawn contour is closed or not.

edit flag offensive delete link more

Question Tools

1 follower

Stats

Asked: 2012-12-28 09:42:30 -0500

Seen: 5,960 times

Last updated: Dec 28 '12