如何使用 const 数获取每个矩阵元素的最小值?

How to get the minimum of each matrix element with a const number?

这段代码是否有 NumPy 库的实现?我的矩阵很大,需要很长时间来迭代!

for i in range (0,x):
    for j in range(0,y):
        V[i, j] = min(V[i][j] + 50,255)

您可以使用 clip():

np.clip(a+50, None, 255)

当然,假设你有一个 numpy.ndarray:

>>> arr = np.random.randint(0, 500, (10,10))
>>> arr
array([[411, 403, 291, 357, 319, 318, 302, 419, 145, 338],
       [388,  93, 487, 442,   0, 125, 174, 329, 178, 326],
       [305, 281, 476,  65, 102, 101, 115, 370, 367, 139],
       [410, 492, 426, 460, 384, 419, 241, 423, 326, 465],
       [263, 127, 166, 364,  11, 100,  85, 303, 328, 287],
       [321,  53, 406, 150, 291, 322,  33,  24,   0, 294],
       [259, 279, 455,  60, 479, 157, 460,  46, 109, 486],
       [203, 309,  53, 336, 116,   0, 326, 282, 305, 324],
       [399, 131, 494, 429, 294, 175, 392, 185,  48, 408],
       [473, 143, 414, 189, 159, 483, 168, 321, 285, 364]])

那么我相信你想要这样的东西:

>>> (arr + 50).clip(max=255)
array([[255, 255, 255, 255, 255, 255, 255, 255, 195, 255],
       [255, 143, 255, 255,  50, 175, 224, 255, 228, 255],
       [255, 255, 255, 115, 152, 151, 165, 255, 255, 189],
       [255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
       [255, 177, 216, 255,  61, 150, 135, 255, 255, 255],
       [255, 103, 255, 200, 255, 255,  83,  74,  50, 255],
       [255, 255, 255, 110, 255, 207, 255,  96, 159, 255],
       [253, 255, 103, 255, 166,  50, 255, 255, 255, 255],
       [255, 181, 255, 255, 255, 225, 255, 235,  98, 255],
       [255, 193, 255, 239, 209, 255, 218, 255, 255, 255]])
>>>

numpy.where() 很酷。您可以执行以下操作:

V[:,:] = np.where(V+50 < 255, V+50, 255)

np.minimumnp.min 的 non-reducing 兄弟:

V = np.minimum(V + 50, 255)

或者 - 如果您愿意 - 您可以这样做 in-place,为中间体节省内存。正如您所说,您的数组非常大可能会有一些好处:

V += 50
np.minimum(V, 255, V)

示例:

>>> np.minimum(np.arange(20) + 10, 18)
array([10, 11, 12, 13, 14, 15, 16, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18,
       18, 18, 18])