繁体   English   中英

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

[英]How to change white images background color to black color in one folder?

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

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)

如果有人可以帮助我,我将不胜感激。谢谢。

看图

您应该使用 HSV 颜色空间,而不是使用 RGB 颜色范围来过滤背景颜色。 选择一个 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)

结果图像:

在此处输入图片说明

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM