Replace all elements of Python NumPy Array that are greater than some value
I have a 2D NumPy array and would like to replace all values in it greater than or equal to a threshold T with 255.0. To my knowledge, the most fundamental way would be:
shape = arr.shape result = np.zeros(shape) for x in range(0, shape): for y in range(0, shape): if arr[x, y] >= T: result[x, y] = 255
What is the most concise and pythonic way to do this?
Is there a faster (possibly less concise and/or less pythonic) way to do this?
This will be part of a window/level adjustment subroutine for MRI scans of the human head. The 2D numpy array is the image pixel data.
I think both the fastest and most concise way to do this is to use Numpy's builtin indexing. If you have a
arr you can replace all elements
>255 with a value
x as follows:
arr[arr > 255] = x
I ran this on my machine with a 500 x 500 random matrix, replacing all values >0.5 with 5, and it took an average of 7.59ms.
In : import numpy as np In : A = np.random.rand(500, 500) In : timeit A[A > 0.5] = 5 100 loops, best of 3: 7.59 ms per loop
★ Back to homepage or read more recommendations: