简体   繁体   English

替换Numpy数组中的多个值

[英]Replace multiple values in Numpy Array

Given the following example 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]]]
)

I want to replace values [0, 0, 0, 255] values with [255, 0, 0, 255] and everything else becomes [0, 0, 0, 0] . 我想替换值[0, 0, 0, 255]值与[255, 0, 0, 255]和其他一切变为[0, 0, 0, 0]

So the desired output is: 因此,所需的输出为:

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

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

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

This solution got close: 该解决方案接近:

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

But it outputs this instead: 但是它改为输出:

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

What's a good way to do this? 有什么好方法吗?

You can find all occurrences of [0, 0, 0, 255] using 您可以使用查找所有出现的[0, 0, 0, 255]

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

Save these positions to a mask , set everything to zero, then place the desired output into the mask positions: 将这些位置保存到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]]])

Here's one way: 这是一种方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM