简体   繁体   中英

How to convert numpy array (image) values in a certain range quickly?

I have a numpy array H_arr representing the following image:

H_arr 图像 (IMG 1)

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).

A small sample of contents in the array is as follows:

array([[[ 9.82194304e-01,  6.16799951e-01,  0.00000000e+00],
        [ 7.51243293e-01,  2.53669262e-01,  0.00000000e+00],
        [-1.90236688e-01, -6.85738802e-01,  0.00000000e+00],
        ...,
        [ 1.08140916e-01,  4.63667512e-01,  0.00000000e+00],
        [ 7.14704990e-01,  3.88218343e-01,  0.00000000e+00],
        [ 1.23196030e+00,  3.89020175e-01,  0.00000000e+00]],

       [[ 6.56815767e-01, -1.04509020e+00,  0.00000000e+00],
        [ 4.86243457e-01, -1.16238987e+00, -5.29288232e-01],
        [-2.55954474e-01, -1.47386789e+00, -8.35296035e-01],
        ...,

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM