Python替换NumPy数组中大于某个值的所有元素实例
我有一个2D(二维) NumPy数组,并希望用255.0替换大于或等于阈值T的所有值。据我所知,最基础的方法是:
shape = arr.shape result = np.zeros(shape) for x in range(0, shape[0]): for y in range(0, shape[1]): if arr[x, y] >= T: result[x, y] = 255
有更简洁和pythonic的方式来做到这一点吗?
有没有更快(可能不那么简洁和/或不那么pythonic)的方式来做到这一点?
这将成为人体头部MRI扫描窗口/等级调整子程序的一部分,2D numpy数组是图像像素数据。
np.maximum(a, 0, a)
要么,
a[a>255] = 255
a[a<0] = 0
第三种解决思路
可以通过使用where功能来达到最快的速度:
例如,在numpy数组中查找大于0.2的项目,并用0代替它们:
import numpy as np nums = np.random.rand(4,3) print np.where(nums > 0.2, 0, nums)
第四种思路
可以考虑使用numpy.putmask:
np.putmask(arr, arr>=T, 255.0)
下面是与Numpy内置索引的性能比较:
In [1]: import numpy as np In [2]: A = np.random.rand(500, 500) In [3]: timeit np.putmask(A, A>0.5, 5) 1000 loops, best of 3: 1.34 ms per loop In [4]: timeit A[A > 0.5] = 5 1000 loops, best of 3: 1.82 ms per loop
以上这篇Python替换NumPy数组中大于某个值的所有元素实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持来客网。