从图像中删除最大轮廓

时间:2015-10-06 11:03:13

标签: python opencv image-processing

我有一个像这样的图像

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)

上面的代码似乎给了我带箭头的相同图像。

如何删除箭头?

1 个答案:

答案 0 :(得分:4)

以下将删除最大轮廓:

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)

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

相关问题