替换 Numpy 数组中的多个值

Replace multiple values in Numpy Array

给定以下示例数组:

import numpy as np

example = np.array(
  [[[   0,    0,    0,  255],
    [   0,    0,    0,  255]],

   [[   0,    0,    0,  255],
    [ 221,  222,   13,  255]],

   [[-166, -205, -204,  255],
    [-257, -257, -257,  255]]]
)

我想用 [255, 0, 0, 255] 替换值 [0, 0, 0, 255] 值,其他所有值都变成 [0, 0, 0, 0].

所以期望的输出是:

[[[   255,    0,    0,  255],
  [   255,    0,    0,  255]],

 [[   255,    0,    0,  255],
  [     0,    0,    0,    0]],

 [[     0,    0,    0,    0],
  [     0,    0,    0,    0]]

这个解决方案很接近:

np.place(example, example==[0, 0, 0,  255], [255, 0, 0, 255])
np.place(example, example!=[255, 0, 0, 255], [0, 0, 0, 0])

但它输出的是:

[[[255   0   0 255],
  [255   0   0 255]],

 [[255   0   0 255],
  [  0   0   0 255]], # <- extra 255 here

 [[  0   0   0   0],
  [  0   0   0   0]]]

执行此操作的好方法是什么?

这是一种方法:

a = np.array([0, 0, 0, 255])
replace = np.array([255, 0, 0, 255])

m = (example - a).any(-1)
np.logical_not(m)[...,None] * replace

array([[[255,   0,   0, 255],
        [255,   0,   0, 255]],

       [[255,   0,   0, 255],
        [  0,   0,   0,   0]],

       [[  0,   0,   0,   0],
        [  0,   0,   0,   0]]])

您可以使用

找到所有出现的[0, 0, 0, 255]
np.all(example == [0, 0, 0, 255], axis=-1)
# array([[ True,  True],
#        [ True, False],
#        [False, False]])

将这些位置保存到 mask,将所有内容设置为零,然后将所需的输出放入 mask 位置:

mask = np.all(example == [0, 0, 0, 255], axis=-1)
example[:] = 0
example[mask, :] = [255, 0, 0, 255]
# array([[[255,   0,   0, 255],
#         [255,   0,   0, 255]],
# 
#        [[255,   0,   0, 255],
#         [  0,   0,   0,   0]],
# 
#        [[  0,   0,   0,   0],
#         [  0,   0,   0,   0]]])