Search code examples
pythonopencvimage-processingbounding-box

Get the real bounding box of a rectangle shaped mask


i have this binary image (numpy array) that represents an approximation of a rectangle :

Mask

I'm trying to extract the real shape of the rectangle but can't seem to find a way. The expected result is the following:

Exected

I'm using this code

contours,_ = cv2.findContours(numpymask.copy(), 1, 1) # not copying here will throw an error
rect = cv2.minAreaRect(contours[0]) # basically you can feed this rect into your classifier
(x,y),(w,h), a = rect # a - angle

box = cv2.boxPoints(rect)
box = np.int0(box) #turn into ints
rect2 = cv2.drawContours(img.copy(),[box],0,(0,0,255),10)

plt.imshow(rect2)
plt.show()

But the resut i'm getting is the following, which i not what i need :

enter image description here

For this i'm using Python with opencv.


Solution

  • This is something i played around with before. It should work with your image.

    import imutils
    import cv2
    # load the image, convert it to grayscale, and blur it slightly
    image = cv2.imread("test.jpg")
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    gray = cv2.GaussianBlur(gray, (5, 5), 0)
    # threshold the image,
    thresh = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY)[1]
    # find contours in thresholded image, then grab the largest
    # one
    cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
        cv2.CHAIN_APPROX_SIMPLE)
    cnts = imutils.grab_contours(cnts)
    c = max(cnts, key=cv2.contourArea)
    # draw the contours of c
    cv2.drawContours(image, [c], -1, (0, 0, 255), 2)
    
    # show the output image
    cv2.imshow("Image", image)
    cv2.waitKey(0)
    

    output