最多 2 个 numpy uint8 数组

Maximum of 2 numpy unint8 arrays

我想获取 2 个 numpy uint8 数组的最大值(0 到 255),但我想排除 255 值。

x1 = np.array([[0, 1], [2, 255]], dtype=np.uint8)
x1 = np.array([[2, 2], [255, 255]], dtype=np.uint8)

result:
array([[2, 2], [2, 255]], dtype=uint8)

如何有效地做到这一点?

我认为你需要np.maximum():

import numpy as np

x1 = np.array([[0, 1], [2, 255]], dtype=np.uint8)
x2 = np.array([[2, 2], [255, 255]], dtype=np.uint8)

print(np.maximum(x1, x2))
#[[  2   2]
# [255 255]]

编辑

在其他答案中你有实际的解决方案,我为多数组使用编辑了它:

x1 = np.array([[0, 1], [2, 255]], dtype=np.uint8)
x2 = np.array([[2, 2], [255, 255]], dtype=np.uint8)
x3 = np.array([[4, 255], [2, 255]], dtype=np.uint8)

reduce(np.maximum, np.stack((x1, x2, x3))+1)-1
#[[  4   2]
# [  2 255]]

这是一个使用上溢和下溢的简单技巧。

>>> np.maximum(x1+1, x2+1)-1
array([[  2,   2],
       [  2, 255]], dtype=uint8)