Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

If the problem you're asking for help with is the contour being filled in, probably the easiest way to make it how you want is to use that filled in contour as a mask on your image:

Mat mask, newImage;
drawContours(mask, vtContours, nSavedContour, Scalar(255), CV_FILLED, 8);
image.copyTo(newImage, mask);

Then you'll have the contour you want in newImage.

Also if you want the largest contour, it's probably easiest to just sort the vector of contours. This is the function I always use for that:

void sortContours(vector<vector<Point>>& contours)
{
    auto contourComparator = [](vector<Point> a, vector<Point> b) { return contourArea(a) > contourArea(b); };
    sort(contours.begin(), contours.end(), contourComparator);
}

Then the largest one will just be the first one in the vector, so it would just be this to make the mask:

sortContours(vtContours);
drawContours(mask, vtContours, 0, Scalar(255), CV_FILLED, 8);

If the problem you're asking for help with is the contour being filled in, probably the easiest way to make it how you want is to use that filled in contour as a mask on your image:

Mat mask, mask = Mat::zeros(image.size(), CV_8U);
Mat newImage;
drawContours(mask, vtContours, nSavedContour, Scalar(255), CV_FILLED, 8);
image.copyTo(newImage, mask);

Then you'll have the contour you want in newImage.

Also if you want the largest contour, it's probably easiest to just sort the vector of contours. This is the function I always use for that:

void sortContours(vector<vector<Point>>& contours)
{
    auto contourComparator = [](vector<Point> a, vector<Point> b) { return contourArea(a) > contourArea(b); };
    sort(contours.begin(), contours.end(), contourComparator);
}

Then the largest one will just be the first one in the vector, so it would just be this to make the mask:

sortContours(vtContours);
drawContours(mask, vtContours, 0, Scalar(255), CV_FILLED, 8);