检测并删除角色周围的矩形

2024-06-01 09:52:08 发布

您现在位置:Python中文网/ 问答频道 /正文

如何删除字符和数字周围的矩形,以便在之后执行OCR?以下是一个例子:

example

我假设这些线是连续的。我试着用OpenCV轮廓来做,但到目前为止,它似乎是一个非常不可靠的算法,严重依赖于图像的噪声、线条的宽度等

我对最通用、最健壮的算法感兴趣。我也可以考虑神经解决方案,但到目前为止,我只发现了一种方法(https://github.com/clovaai/CRAFT-pytorch)来检测和提取字符,在字符被平方/矩形内的字符/数字分割的情况下,它也经常失败。p>


Tags: 图像算法宽度数字解决方案字符神经噪声
1条回答
网友
1楼 · 发布于 2024-06-01 09:52:08

我们可以用findContours来移除它们

我们需要先对图像做一个遮罩。我使用[200255]范围来获得白色背景。然后我腐蚀了面具,以确保盒子之间有足够的间隔

enter image description here

然后我用找到的玩具来拿箱子。我去掉了小轮廓,过滤掉盒子里的数字。我重新画了盒子,里面没有数字

enter image description here

然后,我回到原来的图像上,把蒙着的部分涂成白色

enter image description here

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);

相关问题 更多 >