简体   繁体   中英

Crop simple bounding box with openCV

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

这是它的样子

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

目标

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

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.

An approach is to determine the contour with the largest area then crop around this contour. We can do this by converting the image to grayscale, performing canny edge detection, then some morphological operations to smooth the image. From here we find contours and sort using contour area. To crop the ROI, we simply determine the bounding rectangle coordinates and use Numpy slicing. Here's the result

在此处输入图片说明

import cv2

image = cv2.imread('1.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
canny = cv2.Canny(gray, 120, 255, 1)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
close = cv2.morphologyEx(canny, cv2.MORPH_CLOSE, kernel)

cnts = cv2.findContours(close, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
cnts = sorted(cnts, key=cv2.contourArea)[-1:]
for c in cnts:
    x,y,w,h = cv2.boundingRect(c)
    ROI = image[y:y+h,x:x+w]

cv2.imshow('ROI', ROI)
cv2.waitKey()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM