Ask Your Question

Revision history [back]

Python, eliminate small contours, white matte.

I'm attempting to do the same thing as this person: How to eliminate small contours in a binary image? but with two changes. One, do it in Python (which I'm not a programmer and am barely getting by with Python). But also my image is primarily white and want to keep the black, e.g.:

image description

Desired Result:

image description

Here is the solution in the other thread but can't get it working in Python and believe it will just turn everything black instead of white.

Mat result;
vector<vector<Point> >contours;
vector<Vec4i>hierarchy;
int savedContour = -1;
double maxArea = 0.0;
// Find the largest contour
//
//// findContours will "eat" the input image, so clone the binary Mat, we need it later:
//
findContours(binarayImage.clone(), contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point());
for (int i = 0; i< contours.size(); i++)
{
    double area = contouenter code hererArea(contours[i]);
    if (area > maxArea)
    {
        maxArea = area;
        savedContour = i;
    }
}
// Create mask
drawContours(result, contours, savedContour, Scalar(255), CV_FILLED, 8);

// apply the mask:
binarayImage &= result;