如果一副图像的像素占有很多的灰度级而且分布均匀,那么这样的图像往往有高对比度和多变的灰度色调。直方图均衡化就是一种能仅靠输入图像直方图信息自动达到这种效果的变换函数。它的基本思想是对图像中像素个数多的灰度级进行展宽,而对图像中像素个数少的灰度进行压缩,从而扩展像原取值的动态范围,提高了对比度和灰度色调的变化,使图像更加清晰。
上面的文字来自百度
如下将展示如何使用Python实现:
一共两个文件。
imtools.py
# -- coding: utf-8 --
import numpy as np
def histeq(im, nbr_bins = 256):
'''对一副灰度图像进行值方图均衡化'''
imhist, bins = np.histogram(im.flatten(), nbr_bins, normed = True)
cdf = imhist.cumsum()
cdf = 255 * cdf/cdf[-1]
im2 = np.interp(im.flatten(), bins[:-1], cdf)
return im2.reshape(im.shape), cdf
调用位置
test.py
from PIL import Image
from numpy import *
import imtools
im = array(Image.open('./res/org.jpg').convert('L'))
im2, cdf = imtools.histeq(im)
pil_im = Image.fromarray(im2)
pil_im.show()