python 计算机视觉 1.3.4直方图均衡化

图像灰度变换中一个非常有用的例子就是直方图均衡化。直方图均衡化是指将一幅 图像的灰度直方图变平,使变换后的图像中每个灰度值的分布概率都相同。在对图 像做进一步处理之前,直方图均衡化通常是对图像灰度值进行归一化的一个非常好 的方法,并且可以增强图像的对比度。
在这种情况下,直方图均衡化的变换函数是图像中像素值的累积分布函数(cumulative distribution function,简写为 cdf,将像素值的范围映射到目标范围的归一化操作)。

下面的函数是直方图均衡化的具体实现。

def histeq(im,nbr_bins=256):
    """ 对一幅灰度图像进行直方图均衡化 """  # 计算图像的直方图  imhist,bins = histogram(im.flatten(),nbr_bins,normed=True)
    cdf = imhist.cumsum() # cumulative distribution function  cdf = 255 * cdf / cdf[-1] # 归一化   # 使用累积分布函数的线性插值,计算新的像素值  im2 = interp(im.flatten(),bins[:-1],cdf)
    return im2.reshape(im.shape), cdf

该函数有两个输入参数,一个是灰度图像,一个是直方图中使用小区间的数目。函 数返回直方图均衡化后的图像,以及用来做像素值映射的累积分布函数。注意,函 数中使用到累积分布函数的最后一个元素(下标为 -1),目的是将其归一化到 0...1 范围。

函数使用

#!/usr/bin/python  # -*- coding: utf-8 -*- from PIL import Image
from pylab import *
from PCV.tools import imtools

# 添加中文字体支持 from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r"c:\windows\fonts\SimSun.ttc", size=14)

im = array(Image.open('D:/pictures/gakki.png').convert('L'))  # 打开图像,并转成灰度图像 #im = array(Image.open('D:/pictures/fanghuonv.png').convert('L')) im = array(Image.open('../data/AquaTermi_lowcontrast.JPG').convert('L'))
im2, cdf = imtools.histeq(im)

figure()
subplot(2, 2, 1)
axis('off')
gray()
title(u'原始图像', fontproperties=font)
imshow(im)

subplot(2, 2, 2)
axis('off')
title(u'直方图均衡化后的图像', fontproperties=font)
imshow(im2)

subplot(2, 2, 3)
axis('off')
title(u'原始直方图', fontproperties=font)
#hist(im.flatten(), 128, cumulative=True, normed=True) hist(im.flatten(), 128, normed=True)

subplot(2, 2, 4)
axis('off')
title(u'均衡化后的直方图', fontproperties=font)
#hist(im2.flatten(), 128, cumulative=True, normed=True) hist(im2.flatten(), 128, normed=True)

show()