【问题标题】:Replace image pixel color based on channel condition in Python在Python中根据通道条件替换图像像素颜色
【发布时间】:2020-09-11 15:42:40
【问题描述】:

我有一张 RGB 图像,如何通过比较同一像素的红色和蓝色通道值将像素颜色更改为白色或黑色?

if r_pixel > g_pixel:
    # make pixel white
else:
    # Make pixel black

这是我尝试过的:

img = cv2.imread("car.jpg")
b,g,r = cv2.split(img)
new = np.subtract(r , g)

输出是严格的黑白图像(0 或 255)。

【问题讨论】:

    标签: python opencv


    【解决方案1】:

    我会根据条件使用np.where() 在每个像素处选择2550

    import cv2
    import numpy as np
    
    # Load image
    img = cv2.imread('colorwheel.jpg')
    
    # Wherever R>G, make result white, and black elsewhere
    res = np.where(img[...,2]>img[...,1], 255, 0).astype(np.uint8)
    
    # ALTERNATIVE SOLUTION FOLLOWS
    
    # Or you could generate a Boolean (True/False) array and multiply by 255 to get the same result
    res = ((img[...,2]>img[...,1]) * 255 ).astype(np.uint8)
    

    输入

    结果

    【讨论】:

      【解决方案2】:

      你可以先切片所需的通道,如下图,然后比较两个通道并将结果从布尔值转换为 uint8,然后挤压单例通道并乘以 255:

      r = img[:,:,2:]
      g = img[:,:,1:2]
      new = 255*np.squeeze(r>g,axis=2).astype('uint8')
      

      【讨论】:

        猜你喜欢
        • 2019-04-13
        • 2021-05-04
        • 1970-01-01
        • 2012-05-27
        • 1970-01-01
        • 1970-01-01
        • 2012-09-30
        • 2018-05-11
        • 1970-01-01
        相关资源
        最近更新 更多