Im trying to find an efficient way to scale 2 byte (-32K -> +32K) numpy int arrays to 8 bit (0 -> 255) using a specific scaling function. The very inefficient method that works is (where minVal and maxVal are the min and Max values in the original 2 byte numpy array, and paddingVal in the original will be set to 0):
...
pixel_array = np.zeros( length, dtype=np.int16)
byte_array = np.zeros( length, dtype=np.uint8)
....
i = 0
for val in np.nditer(pixel_array):
value = 0.0
if val == paddingVal:
byte_array[i] = 0
else:
value = 255.0 * ( val - minVal ) / (maxVal - minVal - 1.0)
byte_array[i] = (round(value))
i += 1
I cant figure out how to avoid the loop and still do the if... and apply the scaling function.
thx
byte_array = (255.0 * (pixel_array - minVal) / (maxVal - minVal - 1.0)).astype(np.uint8). You can set the "padding" values afterwards usingbyte_array[pixel_array == paddingVal] = 0. It's not memory-efficient, but it will be much faster than what you're currently doing.numpy.round, but it's not the same as your original code (@jorgeca's answer should give identical results to your original solution, though).