问题
** What I want to do is remove the red box in 5000 images. I wrote a piece of python code for one sample image, but I don't know where got something wrong. I can't realize such purpose. I appreciate any other way to solve this problem.This is the sample image
** '''
import cv2
import numpy as np
img = cv2.imread(r'C:\Users\lenvov\Desktop\baowenti\2.jpg')
# 缩放
rows, cols, channels = img.shape
img = cv2.resize(img, None, fx=0.5, fy=0.5)
img_hsv=cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# lower mask (0-10)
lower_red = np.array([0,50,50])
upper_red = np.array([10,255,255])
mask0 = cv2.inRange(img_hsv, lower_red, upper_red)
# upper mask (170-180)
lower_red = np.array([170,50,50])
upper_red = np.array([180,255,255])
mask1 = cv2.inRange(img_hsv, lower_red, upper_red)
# join my masks
mask = mask0+mask1
Index = np.where(mask != 0)
pix_X = Index[0]
pix_Y = Index[1]
for i in range(len(list(pix_X))):
if i < 305:
img[(pix_X[i], pix_Y[i])] = (1/4 * (img[(pix_X[i]+20, pix_Y[i]+4)] +
img[(pix_X[i]+21, pix_Y[i]+2)] +
img[(pix_X[i]+4, pix_Y[i]+20)] +
img[(pix_X[i]+2, pix_Y[i]+21)])).round()
cv2.imshow('res', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
'''
回答1:
I am not certain what the problem is, but would suggest you replace the red box using "inpainting" - see here
That makes your code look like this:
...
...
# join my masks
mask = mask0+mask1
result = cv2.inpaint(img,mask,3,cv.INPAINT_TELEA)
As you have identified, the red hues wrap around and lie near 180 or 0 and, as a result you are running your range detection twice. One nifty "trick" you can use is to invert the image (by subtracting from 255) before conversion to HSV and then look for cyan colour (i.e. Hue=90 in OpenCV) instead of red. So your code becomes:
# Load image
img = cv2.imread('box.jpg')
# Invert and convert to HSV
img_hsv=cv2.cvtColor(255-img, cv2.COLOR_BGR2HSV)
# Mask all red pixels (cyan in inverted image)
lo = np.uint8([80,30,0])
hi = np.uint8([95,255,255])
mask = cv2.inRange(img_hsv,lo,hi)
# Inpaint red box
result = cv2.inpaint(img,mask,3,cv.INPAINT_TELEA)
Also, if you have 5,000 images to do, I would suggest you consider multiprocessing - there is an example you could use as a basis here.
Keywords: Image processing, Python, OpenCV, inpainting, cv2:inpaint.
来源:https://stackoverflow.com/questions/59235820/remove-the-annotation-box-from-the-picture