Home > Software design >  Remove Yellow rectangle from image
Remove Yellow rectangle from image

Time:05-20

I am using this code to remove this yellow stamp from an image :

import cv2
import numpy as np

# read image
img = cv2.imread('input.jpg')

# threshold on yellow
lower = (0, 200, 200)
upper = (100, 255, 255)
thresh = cv2.inRange(img, lower, upper)

# apply dilate morphology
kernel = np.ones((9, 9), np.uint8)
mask = cv2.morphologyEx(thresh, cv2.MORPH_DILATE, kernel)

# get largest contour
contours = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
big_contour = max(contours, key=cv2.contourArea)
x, y, w, h = cv2.boundingRect(big_contour)

# draw filled white contour on input
result = img.copy()
cv2.drawContours(result, [big_contour], 0, (255, 255, 255), -1)


cv2.imwrite('yellow_removed.png', result)

# show the images
cv2.imshow("RESULT", result)
cv2.waitKey(0)
cv2.destroyAllWindows()

I get the following error:

big_contour = max(contours, key=cv2.contourArea) ValueError: max() arg is an empty sequence

Obviously, it is not detecting any contours, and the contours array is empty, but I could not figure out why that is or how to fix it. Help is appreciated!

CodePudding user response:

Check your lower thresholds. It worked for me for both images when I changed the lower threshold to lower = (0, 120, 120).

CodePudding user response:

The thresholds is the reason due to the second image being darker. Lowering these thresholds captures more of the yellow area, but will still leave some holes when drawing the contour.

lower = (0, 130, 130)

holes left in image

You can fix this by drawing the bounding rectangle instead.

cv2.rectangle(result,(x,y),(x w,y h),(255,255,255),-1)

enter image description here

  • Related