I want a function to take in an image as a numpy array and remap the values to a new range (0, 1) based on a specified maximum and minimum value from the input range. I've got a working function, but I'm iterating through the array and it takes about 10 seconds to complete. Is there a more efficient way to perform this task? Maybe some built in numpy function that I'm not aware of?
This is what I've got:
import numpy as np
def stretch(image, minimum, maximum):
dY = image.shape[0]
dX = image.shape[1]
r = maximum - minimum
image = image.flatten()
for i in range(image.size):
if image[i] > maximum or image[i] < minimum:
image[i] = 1. or 0.
else:
image[i] = (image[i] - minimum) / r
return image.reshape(dY, dX)
I've also tried a version of the above using numpy.nditer instead of manually iterating with the for loop but that seems to be about four times as slow (~40 seconds).
Is there a more efficient way to do this that I'm overlooking? The images I'm working with are about 16 MP. (3520, 4656)