在Numpy,Python中'拉伸'直方图( 关卡)

问题描述 投票:3回答:2

我有灰度图像,其背景为0-255色标,中白色,平均像素颜色值为246;前景是中灰色,平均像素颜色值为186。

我想将每个像素“移动”在246到255之间,每个像素低于186到零,并“拉伸”它们之间的所有内容。是否有任何现成的算法/过程在numpy或python中执行此操作,或者必须“手动”计算新的级别/直方图(如我迄今为止所做的那样)?

这相当于在Gimp或Photoshop中打开水平窗口并分别选择白色和黑色吸管,我们想要制作白色的浅色区域和我们想要变黑的较暗区域:应用程序修改级别/直方图(相应地“拉伸”所选点之间的值)。

我正在尝试的一些图像:

page after page shadow elimination Sampled colours Result

python numpy image-processing
2个回答
1
投票

这是一种方式 -

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

根据OP,标准设定为:

  • 246上方的每个像素“移动”到255,因此247及以上应该成为255
  • 186以下的每个像素到zero,因此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)

1
投票

如果您的图片是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]

对于较小的图像,它更快(在我的设置上它跨越大约100,000灰度像素)直接转换:

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')
© www.soinside.com 2019 - 2024. All rights reserved.