Ask Your Question
0

Python, eliminate small contours, white matte.

asked 2019-11-19 10:03:36 -0600

User284093 gravatar image

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;
edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
1

answered 2019-11-19 10:18:22 -0600

berak gravatar image

updated 2019-11-19 10:22:20 -0600

opencv's findContours() expects white blobs on black bg in your binary image,

you have it the other way round, so feed it an inverted image:

findContours( ~binarayImage, ....

(you also do not need to clone() the image, that idea is a leftover from 2.4 code)

edit flag offensive delete link more

Question Tools

1 follower

Stats

Asked: 2019-11-19 10:03:36 -0600

Seen: 421 times

Last updated: Nov 19 '19