如何截断2D numpy数组的值

nob*_*ody 6 python numpy

我有一个二维numpy数组(uint16),如何将某个障碍(比如255)上的所有值截断到该障碍?其他值必须保持不变.使用嵌套循环似乎是无效的和笨拙的.

And*_*nca 19

实际上有一个特定的方法,'剪辑':

import numpy as np
my_array = np.array([[100, 200], [300, 400]],np.uint16)
my_array.clip(0,255) # clip(min, max)
Run Code Online (Sandbox Code Playgroud)

输出:

array([[100, 200],
       [255, 255]], dtype=uint16)
Run Code Online (Sandbox Code Playgroud)


ImA*_*reg 6

如果你的问题与JBernardo的答案没有关系,那么更常见的方法就是:(编辑之后,我的答案现在与他的答案非常相似)

def trunc_to( my_array, limit ):
    too_high = my_array > limit
    my_array[too_high] = limit

是numpy bool索引的一个很好的介绍链接.


JBe*_*rdo 5

import numpy as np
my_array = np.array([[100, 200], [300, 400]],np.uint16)
my_array[my_array > 255] = 255
Run Code Online (Sandbox Code Playgroud)

输出将是

array([[100, 200],
       [255, 255]], dtype=uint16)
Run Code Online (Sandbox Code Playgroud)