从图像中删除最大轮廓

3

我有这样一张图片

enter image description here

我想要检测并移除这张图片中的箭头,以便最终得到只有文字的图片。

我尝试了以下方法,但它没有起作用。

image_src = cv2.imread("roi.png")
gray = cv2.cvtColor(image_src, cv2.COLOR_BGR2GRAY)
canny=cv2.Canny(gray,50,200,3)
ret, gray = cv2.threshold(canny, 10, 255, 0)
contours, hierarchy = cv2.findContours(gray, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
largest_area = sorted(contours, key=cv2.contourArea)[-1]
mask = np.ones(image_src.shape[:2], dtype="uint8") * 255
cv2.drawContours(mask, [largest_area], -1, 0, -1)
image = cv2.bitwise_and(image_src, image_src, mask=mask)

上述代码似乎会返回带有箭头的相同图像。
如何去掉箭头?

我正在关注这篇文章,所以我使用了bitwse_and http://www.pyimagesearch.com/2015/02/09/removing-contours-image-using-python-opencv/。我将检查我的代码。 - Anthony
1个回答

7
以下是删除最大轮廓的代码:
import numpy as np
import cv2

image_src = cv2.imread("roi.png")

gray = cv2.cvtColor(image_src, cv2.COLOR_BGR2GRAY)
ret, gray = cv2.threshold(gray, 250, 255,0)

image, contours, hierarchy = cv2.findContours(gray, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
mask = np.zeros(image_src.shape, np.uint8)
largest_areas = sorted(contours, key=cv2.contourArea)
cv2.drawContours(mask, [largest_areas[-2]], 0, (255,255,255,255), -1)
removed = cv2.add(image_src, mask)

cv2.imwrite("removed.png", removed)

注意,在这种情况下,最大的轮廓将是整个图像,因此它实际上是第二大的轮廓。


使用cv2.add方法来获取移除的图像可能不适用于箭头填充了黑色的情况,对吧?如果剩余的图像是通过绘制所有剩余轮廓来得到的,那么这种方法是否更适用于各种类型的图像呢? - Anthony
由于掩模是白色的,我希望 黑色+白色=白色。绘制所有剩余轮廓肯定是另一种方法。 - Martin Evans

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接