[英]Python OpenCV - apply colored mask to image
我得到以下东西:
'red'
, 'blue'
等 问 :在将蒙版添加到图像之前,我该如何着色? 明确地:给定颜色字符串,如何将颜色通道添加到二进制蒙版
我知道如何添加蒙版(例如,使用cv2.addWeighted(mask,alpha,image,1-alpha,0,image)
),但我不知道如何使用简单的cv2.addWeighted(mask,alpha,image,1-alpha,0,image)
将二进制蒙版转换为颜色空间'作为输入。 我知道这在rgb = PIL.ImageColor.getrgb(color)
PIL中rgb = PIL.ImageColor.getrgb(color)
,但是我不知道如何使用OpenCV做到这一点!
编辑 :我设法获得通道元组(0,0,0)中的颜色,目前我的解决方法是:
mask = cv2.cvtColor(mask, cv2.COLOR_GRAY2RGB)
mask[np.where((mask == [1,1,1]).all(axis = 2))] = color
cv2.addWeighted(mask,alpha,image,1-alpha,0,image)
但是问题是,现在图像是带有彩色地图的灰度...所以第一行需要交换
您可以使用更简单,更本地化的方法。 如果您在一个通道上应用了不均匀的移位,那么什么是彩色滤光片? 我通常只使用np.power 。 假设img是图像的3D RGB矩阵:
img = np.power(img,[1.5, 1.0, 1.0]) # shift the reds
img = np.power(img,[1.0, 1.5, 1.0]) # shift the greens
img = np.power(img,[1.2, 1.2, 1.0]) # orange type? (I suck at color mixing, you'll find out the one you need to shift) (since all your colors are made from a combination of these three basic ones)
当我发现这个技巧时,我只是停止使用openCV和PIL(顺便提一下,不推荐使用skimage )
要将过滤器仅应用于蒙版部分,可以执行以下操作:
mask = numpy.expand_dims(mask, 2)
mask = numpy.repeat(mask, 3, axis=2) # give the mask the same shape as your image
colors = {"red": [0.1,0.,0.], "blue": [0.,0.,0.1]} # a dictionary for your colors, experiment with the values
colored_mask = numpy.multiply(mask, colors["red"]) # broadcast multiplication (thanks to the multiplication by 0, you'll end up with values different from 0 only on the relevant channels and the right regions)
img = img+colored_mask # element-wise sum (sinc img and mask have the same shape)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.