如何在一个文件夹中将白色图像背景颜色更改为黑色?

问题描述 投票:1回答:1

我想将我的图像背景颜色更改为黑色。我尝试使用自己的代码,但它不起作用,而且它删除了对象。这是我的脚本:

image = cv2.imread("./1.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([220, 220, 220], dtype=np.uint8)
upper_white = np.array([255, 255, 255], dtype=np.uint8)
mask = cv2.inRange(resized, lower_white, upper_white)
res = cv2.bitwise_not(resized, resized, mask)
cv2.imshow('res', res)

如果有人能帮助我,我将非常感激。谢谢。

See the image

python image-processing
1个回答
0
投票

不使用RGB颜色范围来过滤背景颜色,而应使用HSV颜色空间。选择hsv范围以过滤背景颜色。这里简单的实现相同。

image = cv2.imread("D:\Image\VaS38.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)

结果图片:

enter image description here

PS:请注意,在您的情况下,前景物体边界附近的HSV值略有变化,因此最终结果并不完美。可能是您可以更精确地调整HSV颜色范围以获得更好的结果,或者您可以使用前景物体最外边缘作为侵蚀的限制线。

© www.soinside.com 2019 - 2024. All rights reserved.