我使用以下方法来将任意区间 [a, b] 映射到 [c, d] 区间,并进行反向映射:
import numpy as np
def interval_mapping(image, from_min, from_max, to_min, to_max):
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)
一个例子:
image = np.random.randint(0, 255, (3, 3))
image
返回:
array([[186, 158, 187],
[172, 176, 232],
[124, 167, 155]])
现在将其从 [0, 255] 映射到 [0, 1]。
norm_image = interval_mapping(image, 0, 255, 0.0, 1.0)
norm_image
返回:
array([[ 0.72941176, 0.61960784, 0.73333333],
[ 0.6745098 , 0.69019608, 0.90980392],
[ 0.48627451, 0.65490196, 0.60784314]])
现在从[0,1]转回到[0,255]:
orig_image =interval_mapping(norm_image, 0.0, 1.0, 0, 255).astype('uint8')
orig_image
返回:
array([[186, 158, 187],
[172, 176, 232],
[124, 167, 155]], dtype=uint8)
您还可以将其应用于单列的image
并将其映射到[-1.0,1.0]:
col = image[:, 1]
print col
interval_mapping(col, 0, 255, -1.0, 1.0)
返回值:
[158 176 167]
array([ 0.23921569, 0.38039216, 0.30980392])
或者是一个标量:
interval_mapping(1.0, 0, 255, -1.0, 1.0)
返回值:
-0.99215686274509807