Draw single Contour in OpenCV on image

Sebastian Schmitz picture Sebastian Schmitz · Feb 19, 2014 · Viewed 18.4k times · Source

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

Answer

Parmaia picture Parmaia · Jun 24, 2014

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.