3

I have a binary image depicting humans as white blobs and the background as black. I want to "crop" the biggest (or the 3 biggest) blobs from the big image using opencv.

How would one go around doing this?

kaptsea
  • 113
  • 2
  • 11

1 Answers1

2

I am not sure if you found an answer, but here is a basic structure of the code based on what I understood is your requirement. You can modify it as you need.

import numpy as np
import cv2

# load the image
image = cv2.imread("path_to_your_image.png") # if this not a binary image, you can threshold it
output = image.copy()

im2,contours,hierarchy = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

if len(contours) != 0:
    # the contours are drawn here
    cv2.drawContours(output, contours, -1, 255, 3)

    #find the biggest area of the contour
    c = max(contours, key = cv2.contourArea)

    x,y,w,h = cv2.boundingRect(c)
    # draw the 'human' contour (in green)
    cv2.rectangle(output,(x,y),(x+w,y+h),(0,255,0),2)

# show the image
cv2.imshow("Result", output)

cv2.waitKey(0)

Note: The x, y, x+w and y+h give you the extents of the box , so with that those values you can get the region of interest for the largest blob.

Hope this helps!

Adam Merckx
  • 1,122
  • 1
  • 14
  • 31