数字图像处理(二)

今天花了一点时间实现了,对一幅灰度图像进行直方图均衡化处理

import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
from pylab import *
#输入一张图片并且转成一张灰度图像
src=Image.open('G:/实验室学习资料/数字图像处理/lab1/1_1.jpg').convert('L')
img=np.array(src)
arr=img.flatten()
#显示图像
src.show()
data = src.getdata()
data = np.matrix(data)
print(data)

#print("新图像")

data = np.reshape(data,(228,300))
print(data)
new_im = Image.fromarray(data)
# 显示图片
new_im.show()

#开辟新的空间,存放结果图像
result=np.zeros((228,300))

#绘制原始直方图
subplot(231)
plt.hist(arr,bins=256,normed=True,facecolor='blue',alpha=0.75)

#计算图像直方图(每个bins数组的区间值对应一个imhist数组中的强度值)
imhist,bins = histogram(arr,256,normed=True)
#计算累计分布函数
cdf=imhist.cumsum()

#累计函数归一化(由0~1变换至0~255)
cdf = cdf*255/cdf[-1]
#绘制累计分布函数
subplot(232)
plot(bins[:256],cdf)
#依次对每一个灰度图像素值(强度值)使用cdf进行线性插值,计算其新的强度值
#interp(x,xp,yp) 输入原函数的一系列点(xp,yp),使用线性插值方法模拟函数并计算f(x)
im2 = interp(arr,bins[:256],cdf)
#将压平的图像数组重新变成二维数组
im2 = im2.reshape(arr.shape)
# 显示均衡化之后的直方图图像
subplot(233)
hist(im2.flatten(),256)
#显示原始图像
gray()
subplot(234)
imshow(data)
#显示变换后图像
subplot(236)
imshow(im2.reshape((228,300)))
plt.show()

运行结果:

代码上已经附上很详细的注解了,最后我主要再把思路顺一顺。在处理这个问题时,我们做的第一步便是把图片导入,然后对图片进行一系列处理,比如:把它变成我们需要的灰度图,转成我们所需要的矩阵(包括一维,二维),最后便是根据公式进行直方图均衡化处理。代码中有些冗余的代码我是用来测试的,一并贴上去了,大家可以好好看看也可以忽略。

猜你喜欢

转载自blog.csdn.net/weixin_32888153/article/details/84304560