【问题标题】:Replace multiple values in Numpy Array替换 Numpy 数组中的多个值
【发布时间】:2019-06-04 14:00:44
【问题描述】:

给定以下示例数组:

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]]]

有什么好的方法可以做到这一点?

【问题讨论】:

    标签: python numpy numpy-ndarray


    【解决方案1】:

    您可以使用

    找到所有出现的[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]]])
    

    【讨论】:

      【解决方案2】:

      这是一种方法:

      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]]])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-09-11
        • 1970-01-01
        • 2019-09-26
        • 2012-05-07
        • 1970-01-01
        • 1970-01-01
        • 2019-03-30
        • 2011-03-25
        相关资源
        最近更新 更多