Home > Enterprise >  Calculating separated shapes area in a binary mask with opencv
Calculating separated shapes area in a binary mask with opencv

Time:09-22

I am trying to detect human body mask, but my algorithm sometimes makes mistake like the image below. I was thinking if I could calculate individual shapes area (connected white pixels) in the image, I can just keep the largest one and my problem will be solved. Is there a way for that?

enter image description here

CodePudding user response:

You can also use cv2.findContours() to get the outlines of each of the white blobs. The contours come with a lot of extra properties that you can find here:

enter image description here

CodePudding user response:

You can use the connectedComponents function in OpenCV for this purpose.

retval, labels=cv.connectedComponents(image[, labels[, connectivity[, ltype]]])

More details of this function can be found in the documentation. The output image is a labelled image where each connected component is given a label. The output retval is the total number of labels (also number of connected components).

Then all you have to do is to iterate through the connected components to find the one with most pixels.

  • Related