import os from PIL import Image from numpy import * 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] #归一化,函数中使用累计分布函数的最后一个元素(下标为-1,目标是 # 将其归一化到0-1范围 ) # 使用累计分布函数的线性插值,计算新的像素值 im2=interp(im.flatten(),bins[:-1],cdf) # im2 is an array return im2.reshape(im.shape),cdf
如果想显示直方图均衡化后的图像,需要把array转为图像
因为自己把histeq 函数放到imtools,py中去了,所以调用的时候,需要import imtools
from PIL import Image from numpy import * from pylab import * import imtools import matplotlib.pyplot as plt im =array(Image.open('cat.jpg').convert('L')) im2,cdf=imtools.histeq(im) im21=Image.fromarray(im2) # 将array转化为图像 im21.show()
# -*- coding: utf-8 -*- from PIL import Image from numpy import * from pylab import * import imtools import matplotlib.pyplot as plt im =array(Image.open('cat.jpg').convert('L')) im2,cdf=imtools.histeq(im) im20=Image.fromarray(im) # 未直方图均衡化的图像 im21=Image.fromarray(im2) #直方图均衡化后的 将array转化为图像 plt.figure(num='cat') plt.subplot(1,2,1) plt.title("Before the experiment") plt.axis('off') plt.imshow(im,plt.cm.gray) plt.subplot(1,2,2) plt.title("After the experiment") plt.imshow(im2,plt.cm.gray) plt.axis('off') plt.show()