Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw single Contour in OpenCV on image

What is the best way to draw a single contour in OpenCV? As far as i can see drawContours can only handle multiple contours.

Background: I want to change my code to a for each loop. The old code:

//vector<vector<Point> > contours = result of findContours(...)
for (int i = 0; i < contour.size; i++){
    if(iscorrect(contours[i])){
        drawContours(img, contours, i, color, 1, 8, hierarchy);
    }
 }

The way presented in this mailing list is pretty ugly:

for (vector<Point> contour : contours){
     if(iscorrect(contour)){
          vector<vector<Point> > con = vector<vector<Point> >(1, contour);
          drawContours(img, con, -1, color, 1, 8);
     }
}

Is there a cleaner way to draw single contours (vector< Point> Object)?

like image 241
Sebastian Schmitz Avatar asked Feb 19 '14 16:02

Sebastian Schmitz


People also ask

How do you draw contour on a picture?

To draw the contours, cv. drawContours function is used. It can also be used to draw any shape provided you have its boundary points. Its first argument is source image, second argument is the contours which should be passed as a Python list, third argument is index of contours (useful when drawing individual contour.

What is a contour in an image?

Contours are defined as the line joining all the points along the boundary of an image that are having the same intensity. Contours come handy in shape analysis, finding the size of the object of interest, and object detection.

How does findContours work in OpenCV?

To put in simple words findContours detects change in the image color and marks it as contour. As an example, the image of number written on paper the number would be detected as contour. The part that you want to detect should be white like above numbers in 1st image.


2 Answers

I had the same question, and the better way that I've found until now, is this:

for (vector<Point> contour : contours){
  if(iscorrect(contour)){
    drawContours(img, vector<vector<Point> >(1,contour), -1, color, 1, 8);
  }
}

This is almost the same that you have, but one line less.

My first thought was to use Mat(contour) but it didn't work.

If you've found a better way to do it, publish it here and share the wisdom.

like image 175
Parmaia Avatar answered Sep 21 '22 02:09

Parmaia


With OpenCV 3.0 polylines() is more flexible, and we can do, e.g.:

vector<Point> approx;
polylines(frame, approx, true, color, 1, 8);

In your loop this would be:

for (vector<Point> contour : contours) {
    if (iscorrect(contour)) {
        polylines(frame, approx, true, color, 1, 8);
    }
}
like image 37
br1 Avatar answered Sep 21 '22 02:09

br1