Python:使用OpenCV删除边界框

时间:2018-06-17 18:33:37

标签: python opencv

我面临一个问题,即删除一些边界方块,图像中的矩形包含方框

enter image description here

我将此代码应用于图片

# read image and convert to gray
img = cv2.imread('total.png',cv2.IMREAD_UNCHANGED)

# threshold the gray image to binarize, and negate it

#binary = remove_line(img)
_,binary = cv2.threshold(img, 150, 255, cv2.THRESH_BINARY)
binary = cv2.bitwise_not(binary)

# find external contours of all shapes
_,contours,_ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

# create a mask for floodfill function, see documentation
h,w= img.shape
mask = np.zeros((h+2,w+2), np.uint8)

# determine which contour belongs to a square or rectangle
for cnt in contours:
    poly = cv2.approxPolyDP(cnt, 0.05*cv2.arcLength(cnt,True),True)
    if len(poly) == 4:
        # if the contour has 4 vertices then floodfill that contour with black color
        cnt = np.vstack(cnt).squeeze()
        _,binary,_,_ = cv2.floodFill(binary, mask, tuple(cnt[0]), 0)

# convert image back to original color
binary = cv2.bitwise_not(binary)

结果似乎是那样的

enter image description here

我想完全删除图片中退出的所有框

0 个答案:

没有答案