def stretch(a, lower_thresh, upper_thresh):
r = 255.0/(upper_thresh-lower_thresh+2) # unit of stretching
out = np.round(r*(a-lower_thresh+1)).astype(a.dtype) # stretched values
out[a<lower_thresh] = 0
out[a>upper_thresh] = 255
return out
将每个像素值大于 246
的像素变为 255
,因此大于等于 247
的像素应变为 255
。
将每个像素值小于 186
的像素变为 0
,因此小于等于 185
的像素应变为 0
。
因此,基于上述两个要求,186
应该变成大于 0
的某个值,以此类推直到 246
,它应该比 255
小。
或者,我们也可以使用 np.where
来使代码更简洁 -
def stretch(a, lower_thresh, upper_thresh):
r = 255.0/(upper_thresh-lower_thresh+2) # unit of stretching
out = np.round(r*np.where(a>=lower_thresh,a-lower_thresh+1,0)).clip(max=255)
return out.astype(a.dtype)
示例运行 -
# check out first row input, output for variations
In [216]: a
Out[216]:
array([[186, 187, 188, 246, 247],
[251, 195, 103, 9, 211],
[ 21, 242, 36, 87, 70]], dtype=uint8)
In [217]: stretch(a, lower_thresh=186, upper_thresh=246)
Out[217]:
array([[ 4, 8, 12, 251, 255],
[255, 41, 0, 0, 107],
[ 0, 234, 0, 0, 0]], dtype=uint8)
L, H = 186, 246
lut = np.r_[0:0:(L-1)*1j, 0.5:255.5:(H-L+3)*1j, 255:255:(255-H-1)*1j].astype('u1')
# example
from scipy.misc import face
f = face()
rescaled = lut[f]
fsmall = (f[::16, ::16].sum(2)//3).astype('u1')
slope = 255/(H-L+2)
rescaled = ((1-L+0.5/slope+fsmall)*slope).clip(0, 255).astype('u1')