def histeq(im,nbr_bins=256):
#计算图像的直方图
imhist,bins = histogram(im.flatten(),nbr_bins,normed=True)
cdf = imhist.cumsum() #累计分布函数
cdf = 255 * cdf / cdf[-1] #归一化
#使用累计分布函数的线性插值,计算新的像素
im2 = interp(im.flatten(),bins[:-1],cdf)
return im2.reshape(im.shape),cdf
以上代码我定义在imtools.py文件里并且放在了python2.7里
然后我在num.py里引用他
Python code?
1
2
3
4
5
6
7
8
9
10
from PIL import Image
from pylab import *
from numpy import *
import imtools
im= array(Image.open('E:\\daima\\pydaima\\shijue\\tupian1\\gang2.jpg').convert('L'))
im2,cdf =imtools.histeq(im)
出现以下错误:
Traceback (most recent call last):
File "<pyshell#56>", line 1, in <module>
a=imtools.histeq(im)
File "E:\daima\pydaima\shijue\imtools.py", line 32, in histeq
NameError: global name 'histogram' is not defined
用一下代码解决:import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
import scipy.stats as st
sim = st.gamma(1,loc=0,scale=0.8) # Simulated
obs = st.gamma(2,loc=0,scale=0.7) # Observed
x = np.linspace(0,4,1000)
simpdf = sim.pdf(x)
obspdf = obs.pdf(x)
plt.plot(x,simpdf,label='Simulated')
plt.plot(x,obspdf,'r--',label='Observed')
plt.title('PDF of Observed and Simulated Precipitation')
plt.legend(loc='best')
plt.show()
plt.figure(1)
simcdf = sim.cdf(x)
obscdf = obs.cdf(x)
plt.plot(x,simcdf,label='Simulated')
plt.plot(x,obscdf,'r--',label='Observed')
plt.title('CDF of Observed and Simulated Precipitation')
plt.legend(loc='best')
plt.show()
# Inverse CDF
invcdf = interp1d(obscdf,x)
transfer_func = invcdf(simcdf)
plt.figure(2)
plt.plot(transfer_func,x,'g-')
plt.show()