I have a numpy array H_arr
representing the following image:
and I wish to convert its values in the range [0,1], let's call this new array as New_arr
, in such a way that the original image remains intact. What I mean is that the exact same image (IMG 1) should be displayed when I use plt.imshow(New_arr)
.
The data type of H_arr
is float32, with H_arr.min()
giving -24.198463 and H_arr.max()
giving 26.153196. H_arr.shape
gives (960, 1280, 3).
I had earlier thought that I would use the following formula to convert it to the 0-1 range:
newvalue= (new_max-new_min)/(max-min)*(value-max) new_max
and implement it as:
New = np.zeros((H_arr.shape[0],H_arr.shape[1],H_arr.shape[2]),dtype = float)
for i in range(H_arr.shape[0]):
for j in range(H_arr.shape[1]):
for k in range(H_arr.shape[2]):
New[i][j][k]= (1-0)/(H_arr.max()-H_arr.min())*(H_arr[i][j][k]-H_arr.max()) 1
But this is computationally quite expensive. Any input on how I should go about converting the original array is appreciated.
Edit: After incorporating the answers below, I can do it quite quickly within the [0,1] range, but the image drastically changes to
How do I make sure that my image remains the same as before?
CodePudding user response:
You can apply your formular to the entire array at once. No loop required, just remove the indices:
New= (1-0)/(H_arr.max()-H_arr.min())*(H_arr-H_arr.max()) 1
CodePudding user response:
You can go directly without loops
import numpy as np
shape = 256, 256, 3
vmin, vmax = -24.198463, 26.153196
arr = np.random.rand(*shape) * (vmax - vmin) vmin
# Actual vmin and vmax, due to random
vmin, vmax = arr.min(), arr.max()
# Scaling in [0, 1]
scaled_01 = (arr - vmin) / (vmax - vmin)
print(f"{scaled_01.min() = }")
print(f"{scaled_01.max() = }")
# Scaling into new [vmin, vmax]
vmin_new, vmax_new = 10, 34
scaled = ((arr - vmin) / (vmax - vmin)) * (vmax_new - vmin_new) vmin_new
print(f"{scaled.min() = }")
print(f"{scaled.max() = }")
scaled_01.min() = 0.0
scaled_01.max() = 1.0
scaled.min() = 10.0
scaled.max() = 34.0