【问题标题】:Quickest way to convert black pixels to white using NumPy使用 NumPy 将黑色像素转换为白色的最快方法
【发布时间】:2019-10-17 05:38:43
【问题描述】:

我有一个 RGB 彩色图像掩码 mask_color,形状 (4,4,3)。如何快速将所有黑色像素[0,0,0] 转换为白色[255,255,255],而不使用任何循环,无需额外的包,最好是 NumPy 方式?

mask_color = np.array([
 [
  [0,0,0],
  [128,0,255],
  [0,0,0],
  [0,0,0]
 ],
 [
  [0,0,0],
  [0,0,0],
  [0,0,0],
  [0,0,0]
 ],
 [
  [0,0,0],
  [50,128,0],
  [0,0,0],
  [0,0,0]
 ],
 [
  [0,0,0],
  [0,0,0],
  [245,108,60],
  [0,0,0]
 ]
])

plt.imshow(mask_color)
plt.show()

white_bg_mask_color = # do something
plt.imshow(white_bg_mask_color)
plt.show()

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    你可以使用 np.where:

    >>> np.where(mask_color.any(-1,keepdims=True),mask_color,255)
    array([[[255, 255, 255],
            [128,   0, 255],
            [255, 255, 255],
            [255, 255, 255]],
    
           [[255, 255, 255],
            [255, 255, 255],
            [255, 255, 255],
            [255, 255, 255]],
    
           [[255, 255, 255],
            [ 50, 128,   0],
            [255, 255, 255],
            [255, 255, 255]],
    
           [[255, 255, 255],
            [255, 255, 255],
            [245, 108,  60],
            [255, 255, 255]]])
    

    【讨论】:

      【解决方案2】:

      你也可以使用如下的布尔索引来实现

      mask_color[np.all(mask_color==0, axis=2)] = 255
      mask_color
      

      【讨论】:

        猜你喜欢
        • 2019-12-13
        • 1970-01-01
        • 2019-03-28
        • 2018-09-28
        • 2018-12-23
        • 2020-05-25
        • 2013-09-17
        • 1970-01-01
        相关资源
        最近更新 更多