I use the following to map to and from any interval [a, b] --> [c, d] and back:
import numpy as np
def interval_mapping(image, from_min, from_max, to_min, to_max):
# map values from [from_min, from_max] to [to_min, to_max]
# image: input array
from_range = from_max - from_min
to_range = to_max - to_min
scaled = np.array((image - from_min) / float(from_range), dtype=float)
return to_min + (scaled * to_range)
An example:
image = np.random.randint(0, 255, (3, 3))
image
returns:
array([[186, 158, 187],
[172, 176, 232],
[124, 167, 155]])
Now map this from [0, 255] to [0, 1]
norm_image = interval_mapping(image, 0, 255, 0.0, 1.0)
norm_image
returns:
array([[ 0.72941176, 0.61960784, 0.73333333],
[ 0.6745098 , 0.69019608, 0.90980392],
[ 0.48627451, 0.65490196, 0.60784314]])
now from [0, 1] back to [0, 255]:
orig_image =interval_mapping(norm_image, 0.0, 1.0, 0, 255).astype('uint8')
orig_image
returns:
array([[186, 158, 187],
[172, 176, 232],
[124, 167, 155]], dtype=uint8)
You could also use it one a single column of image
and map it to [-1.0, 1.0]:
col = image[:, 1]
print col
interval_mapping(col, 0, 255, -1.0, 1.0)
returns:
[158 176 167]
array([ 0.23921569, 0.38039216, 0.30980392])
or a scalar:
interval_mapping(1.0, 0, 255, -1.0, 1.0)
returns:
-0.99215686274509807