如何用常数求每个矩阵元素的最小值?

2024-10-03 11:23:36 发布

您现在位置:Python中文网/ 问答频道 /正文

这个代码是否有numpylib实现?我的矩阵非常大,需要很长时间来迭代!你知道吗

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

Tags: 代码inforrange矩阵minnumpylib
3条回答

当然,假设你有一个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)

您可以使用clip()

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

相关问题 更多 >