Search code examples
pythonopencvimage-processingcropcontour

Crop simple bounding box with openCV


I have some images with a black background and some text in the corner:

This is what it looks like

I'm trying to do a rectangular crop to make it look like:

Goal

The text on the sides as well as the window dimensions are of varying sizes. My code isn't cropping correctly, what am I doing wrong?

I've tried removing the text in the bottom right corner first and cropping, that doesn't work either.

def crop_cont(img):
     gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
     _,thresh = cv2.threshold(gray,15,255,cv2.THRESH_BINARY)

     _, contours, _= cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
     cnt = contours[0]

     x,y,w,h = cv2.boundingRect(cnt)

     crop = img[y:y+h,x:x+w]

return crop

Solution

  • Your code is in general ok. The issue is that you are using contours[0]. You have to find the right contour (there are more than one). In this particular example, the right contour is the biggest one. Just iterate all found contours and find the one with the biggest area.