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)?
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.
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.
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.
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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With