使用NumPy将黑色像素转换为白色的最快方法

2024-05-10 01:27:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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()

enter image description here

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

enter image description here


Tags: numpyshow方式pltmaskrgb像素彩色图像
2条回答

您也可以像下面这样使用布尔索引

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

您可以使用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]]])

相关问题 更多 >