Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 487
Anthony Avatar asked Dec 06 '25 02:12

Anthony


1 Answers

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.

like image 134
Martin Evans Avatar answered Dec 08 '25 16:12

Martin Evans



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!