一、直方图
1、基本原理
图像的直方图用来表征该图像像素值的分布情况。用一定数目的小区间(bin)来指定表征像素值的范围,每个小区间会得到落入该小区间表示范围的像素数目。该(灰度)图像的直方图可以使用hist()函数绘制:
figure()
hist(im.flatten(),128)
show()
hist()函数的第二个参数指定小区间的数目。需要注意的是,因为hist()只接受一维数组作为输入,所以我们在绘制图像直方图之前,必须先对图像进行压平处理。flatten()方法将任意数组按照行优先准则转换成一维数组。
2、代码实现
from PIL import Image
from pylab import *
plt.rcParams['font.sans-serif'] = 'Simsun'#设置字体为宋体
im = array(Image.open(r'C:\Users\HJ\Pictures\picture.jpg').convert('L')) # 读取图像到数组中
print(im)
#新建一个图像
figure()
subplot(121)
#不使用颜色信息
gray()
#在原点的左上角显示轮廓图像
contour(im, origin='image')
axis('equal') # 自动调整比例
axis('off') # 去除x、y轴上的刻度
title(u'图像轮廓')
subplot(122)
hist(im.flatten(), 128)
print(im.flatten())
title(u'图像直方图')
plt.xlim([0, 300])
plt.ylim([0, 60000])
show()
3、运行结果
原图
运行结果
二、高斯滤波
1、基本原理
高斯滤波是一种线性平滑滤波,适用于消除高斯噪声,广泛应用于图像处理的减噪过程。 通俗的讲,高斯滤波就是对整幅图像进行加权平均的过程,每一个像素点的值,都由其本身和邻域内的其他像素值经过加权平均后得到。高斯滤波的具体操作是:用一个模板(或称卷积、掩模)扫描图像中的每一个像素,用模板确定的邻域内像素的加权平均灰度值去替代模板中心像素点的值。
2、代码实现
import cv2
import matplotlib.pyplot as plt
im = cv2.imread(r"C:\Users\HJ\Pictures\picture.jpg")
# 高斯滤波
img = cv2.GaussianBlur(im, (5, 5), 0)
plt.subplot(121)
plt.imshow(im)
plt.subplot(122)
plt.imshow(img)
plt.show()
3、运行结果
三、直方图均衡化
1、基本原理
图像灰度变换中一个非常有用的例子就是直方图均衡化。直方图均衡化是指将一幅灰度图像的灰度直方图变平,使变换后的图像中每个灰度值的分布概率都相同。在对图像做进一步处理之前。直方图均衡化通常是对图像灰度值进行归一化的一个非常好的方法,并且可以增强图像的对比度。使用直方图均衡化之后图像会变得更清晰。
2、代码实现
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(r'C:\Users\HJ\Pictures\picture.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, density=True)
subplot(2, 2, 4)
axis('off')
title(u'均衡化后的直方图', fontproperties=font)
hist(im2.flatten(), 128, density=True)
show()