Anthony
Anthony

Reputation: 36008

removing largest contour from an image

I have an image such as this

enter image description here

I am trying to detect and remove the arrow from this image so that I end up with an image that just has the text.

I tried the below approach but it isn't working

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)

The above code seems to give me back the same image WITH the arrow.

How can I remove the arrow?

Upvotes: 3

Views: 8485

Answers (1)

Martin Evans
Martin Evans

Reputation: 46779

The following will remove the largest contour:

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)

Note, the largest contour in this case will be the whole image, so it is actually the second largest contour.

Upvotes: 7

Related Questions