目录
一.图像基础处理操作
1.1.图像读取:
1.2.灰度变化:
1.3.图片显示:
1.4.相关代码:
二.图像直方图:
2.1.直方图相关介绍:
2.2.相关代码:
2.3.运行结果:
三.直方图均衡化:
3.1.运行结果:
3.2.相关代码:
四. 高斯滤波:
4.1.运行结果:
4.2.相关代码:
一.图像基础处理操作
本次实验使用的是Python语言的PIL(Python Image Library)库,PIL库支持图像储存、显示和处理,他能够处理几乎所有图片格式,可以完成对图像的缩放、剪裁、叠加以及向图像添加线条、图像和文字等操作。
1.1.图像读取:
from PIL import Image
img = Image.open('jmu.jpg')
Image类是PIL中的核心类,上述为对图片的读取操作;
1.2.灰度变化:
图像的颜色转换可以用convert()方法实现,需要读取图像的灰度图像,可以在.open后加入convert(‘L’);
img = Image.open('jmu.jpg').convert('L')
1.3.图片显示:
plt.imshow(img1)
原图像显示和图像灰度图显示结果:
由于 plt是直接显示三通道的图像,灰度图是单通道的,可以使用
plt.imshow(img2,plt.cm.gray)
来对灰度图显示;
1.4.相关代码:
from PIL import Image
import matplotlib.pyplot as plt
img1 = Image.open('jmu.jpg')
img2 = Image.open('jmu.jpg').convert('L')
plt.subplot(1,2,1)
plt.title('jmu initial')
plt.imshow(img1)
plt.subplot(1,2,2)
plt.title('jmu trans')
plt.imshow(img2,plt.cm.gray)
plt.show()
二.图像直方图:
2.1.直方图相关介绍:
2.1.直方图相关介绍:
对于一幅灰度图像,可以表示为I(x,y)。I是图像的强度大小。灰度直方图就是统计不同灰度的分布概率。比如对于一个像素bit位为8的图像,那么其灰度范围就是从0~255.灰度直方图就是统计每个灰度级拥有的像素比例。通过直方图可以直观的反映出图像的明暗程度,比如0如果概率大,就说明图像偏暗,255概率大,就说明图像偏亮。
(灰度)图像的直方图可以直接用hist()函数来绘制:
plt.hist(img3.flatten(), 128)
因为hist()只接受一维数组作为输入,绘制直方图之前,需要先对图像进行压平处理,flatten()将任意数组按照优先准则转化为一维数组;其中读取的图像应该是数组值;
2.2.相关代码:
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
img2 = Image.open('jmu.jpg').convert('L')
img3 = np.array(img2)
plt.hist(img3.flatten(), 128)
plt.show()
2.3.运行结果:
三.直方图均衡化:
直方图均衡化是将原图像通过某种变换,得到一幅灰度直方图为均匀分布的新图像的方法。
def histeq(img,nbr_bins=256):
# 计算图像的直方图
imhist,bins = np.histogram(img.flatten(), nbr_bins, density=True)
# 累计分布函数
cdf = imhist.cumsum()
cdf = 255 * cdf / cdf[-1] # 归一化
# 使用累积分布函数的线性插值,计算新的像素值
img2 = np.interp(img.flatten(), bins[:-1], cdf)
return img2.reshape(img.shape),cdf
3.1.运行结果:
对比均衡化后图像与原图像的效果:
3.2.相关代码:
img3 = np.array(img2)
img4,cdf = histeq(img3)
# plt.hist(img3.flatten(), 128)
plt.subplot(2,2,1)
plt.title('jmu initial')
plt.imshow(img3,plt.cm.gray)
plt.subplot(2,2,2)
plt.title('jmu trans')
plt.imshow(img4,plt.cm.gray)
plt.subplot(2,2,3)
plt.title('jmu trans hist')
plt.hist(img4.flatten(), 128)
plt.subplot(2,2,4)
plt.title('jmu trans hist')
plt.hist(img4.flatten(), 128)
plt.show()
四. 高斯滤波:
高斯滤波是一种线性平滑滤波,适用于消除高斯噪声,广泛应用于的图像处理减噪过程。 可以简单的理解为,高斯滤波就是对整幅图像进行加权平均的过程,每一个像素点的值,都由其本身和邻域内的其他像素值经过加权平均后得到
高斯滤波的具体操作是:用一个用户指定的模板(或称卷积、掩膜)去扫描图像中的每一个像素,用模板确定的邻域内像素的加权平均灰度值去替代模板中心像素点的值。
python中SciPy有用来做滤波操作的scipy.ndimage.filters 模块。该模块使用快速一维分离的方式来计算卷积。



