我想把图像背景改成黑色。我尝试了一些代码,但它不起作用,有时它会删除对象。这张图片的背景可能会因地点的不同而不同。出于好奇心,我是否需要让机器学习来去除这类图像的背景以获得更好的结果?

import numpy as np
import cv2
image = cv2.imread(r'D:/IMG_6334.JPG')
r = 150.0 / image.shape[1]
dim = (150, int(image.shape[0] * r))
resized = cv2.resize(image, dim, interpolation=cv2.INTER_AREA)
lower_white = np.array([80, 1, 1],np.uint8) #lower hsv value
upper_white = np.array([130, 255, 255],np.uint8) #upper hsv value
hsv_img = cv2.cvtColor(resized,cv2.COLOR_BGR2HSV) #rgb to hsv color space
#filter the background pixels
frame_threshed = cv2.inRange(hsv_img, lower_white, upper_white)
kernel = np.ones((5,5),np.uint8)
#dilate the resultant image to remove noises in the background
#Number of iterations and kernal size will depend on the backgound noises size
dilation = cv2.dilate(frame_threshed,kernel,iterations = 2)
resized[dilation==255] = (0,0,0) #convert background pixels to black color
cv2.imshow('res', resized)
cv2.waitKey(0)发布于 2021-04-14 12:03:48
这本身就是一个独立的主题。图像遮片就是你要找的东西。这是用来转换你的背景到黑色和你的前景到白色(在这种情况下,你不必这样做)。请查看此网站http://alphamatting.com/,其中提供了所有最先进的遮片算法,并尝试在您的代码中实现它。我会说这真的是很长的路线,所以我可以说更好的解决方案,如果你提到你到底打算做什么后,删除图像的背景。
https://stackoverflow.com/questions/67085311
复制相似问题