代码之家  ›  专栏  ›  技术社区  ›  gustavz

Python OpenCV-将彩色遮罩应用于图像

  •  0
  • gustavz  · 技术社区  · 8 年前

    我得到了以下东西:

    • 与图像大小相同的二进制掩码
    • 'red' , 'blue' 等

    :如何在将遮罩添加到图像之前对其着色? 显式:在给定颜色字符串的情况下,如何向二进制掩码添加颜色通道

    我知道如何添加遮罩(例如 cv2.addWeighted(mask,alpha,image,1-alpha,0,image) ),但我不知道如何使用简单的颜色“字符串”作为输入将二进制掩码转换为颜色空间。我知道这在PIL和 rgb = PIL.ImageColor.getrgb(color)

    :

    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)
    

    但问题是,现在的图像是灰色的,带有彩色地图。。。 所以第一行需要交换

    1 回复  |  直到 8 年前
        1
  •  2
  •   zar3bski    8 年前

    您可以使用更简单、更自然的方法。如果在一个通道上应用的偏移不一致,那么什么是颜色过滤器?我通常只使用 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)