我们可以使用 findContours 删除它们以获取框。
我们需要先制作图像的蒙版。我正在使用 [200, 255] 范围来获取白色背景。然后我腐蚀了遮罩,以确保盒子之间有足够的间隔。
然后我使用 findContours 来获取这些框。我删除了小轮廓以过滤掉框内的数字。我重新绘制了没有数字的方框。
然后我返回原始图像并将蒙版区域变白。
import cv2
import numpy as np
# load image
img = cv2.imread("numbers.png");
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY);
mask = cv2.inRange(gray, 200, 255);
# erode to enhance box separation
kernel = np.ones((3,3), np.uint8);
mask = cv2.erode(mask, kernel, iterations = 1);
# contours OpenCV3.4, if you're using OpenCV 2 or 4, it returns (contours, _)
_, contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE);
# only take big boxes
cutoff = 250;
big_cons = [];
for con in contours:
area = cv2.contourArea(con)
if area > cutoff:
big_cons.append(con);
print(area);
# make a mask
redraw = np.zeros_like(mask);
cv2.drawContours(redraw, big_cons, -1, (255), -1);
redraw = cv2.bitwise_not(redraw);
img[redraw == 255] = (255,255,255); # replace with whatever color you want as your background
# show
cv2.imshow("Image", img);
cv2.imshow("Mask", mask);
cv2.imshow("redraw", redraw);
cv2.waitKey(0);