直方图
原理
直方图是数值数据分布的精确图形表示。 这是一个连续变量(定量变量)的概率分布的估计,并且被卡尔·皮尔逊首先引入。它是一种条形图。
图像的直方图用来表征该图像像素值的分布情况。用一定数目的小区间(bin)来指定表征像素值的范围,每个小区间会得到落入该小区间表示范围的像素数目。该(灰度)图像的直方图可以使用 hist() 函数绘制:基本的图像操作和处理 hist() 函数的第二个参数指定小区间的数目。需要注意的是,因为 hist() 只接受一维数组作为输入,所以我们在绘制图像直方图之前,必须先对图像进行压平处理。flatten() 方法将任意数组按照行优先准则转换成一维数组。
代码实现
from PIL import Image
from matplotlib.font_manager import FontProperties
from pylab import *
from numpy import array
font = FontProperties(fname=r"c:\windows\fonts\SimSun.ttc", size=14)
# 中文乱码
im = array(Image.open('1.jpg').convert('L'))
figure()
subplot(121)
gray() #不使用颜色信息
contour(im, origin='image') #显示轮廓图像
axis('equal')
axis('off') #坐标轴不显示
title('原图轮廓',fontproperties=font)
subplot(122)
hist(im.flatten(),128)
title('图像直方图',fontproperties=font )
show()
原图
实验结果
均衡化
原理
图像灰度变换中一个非常有用的例子就是直方图均衡化。直方图均衡化是指将一幅图像的灰度直方图变平,使变换后的图像中每个灰度值的分布概率都相同。在对图像做进一步处理之前,直方图均衡化通常是对图像灰度值进行归一化的一个非常好的方法,并且可以增强图像的对比度。在这种情况下,直方图均衡化的变换函数是图像中像素值的累积分布函数(cumulative distribution function,简写为 cdf,将像素值的范围映射到目标范围的归一化操作)。
代码实现
from PCV.tools import imtools
from PIL import Image
from matplotlib.font_manager import FontProperties
from pylab import *
from numpy import array
font = FontProperties(fname=r"c:\windows\fonts\SimSun.ttc", size=14)
im = array(Image.open('1.jpg').convert('L'))
im2,cdf = imtools.histeq(im)
figure()
subplot(221)
axis('off')
gray()
title('原始图片',fontproperties=font)
imshow(im)
subplot(222)
axis('off')
title('均衡化后图片', fontproperties=font)
imshow(im2)
subplot(223)
title('原图直方图',fontproperties=font)
hist(im.flatten(),128,density=True)
subplot(224)
title('均衡化直方图',fontproperties=font)
hist(im2.flatten(),128,density=True)
show()
实验结果
高斯模糊
原理
图像的高斯模糊是非常经典的图像卷积例子。本质上,图像模糊就是将(灰度)图像 I 和一个高斯核进行卷积操作:
其中 * 表示卷积操作;Gσ 是标准差为 σ 的二维高斯核,定义为 :
高斯模糊通常是其他图像处理操作的一部分,比如图像插值操作、兴趣点计算以及很多其他应用。SciPy 有用来做滤波操作的 scipy.ndimage.filters 模块。该模块使用快速一维分离的方式来计算卷积。
代码实现
from PIL import Image
from pylab import *
from numpy import array, uint8, zeros
from scipy.ndimage import filters
from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r"c:\windows\fonts\SimSun.ttc", size=14)
im = array(Image.open('1.jpg').convert('L'))
figure()
gray()
subplot(1, 4, 1)
axis('off')
title('原图', fontproperties=font)
imshow(im)
for bi, blur in enumerate([2, 5, 10]):
im2 = zeros(im.shape)
im2 = filters.gaussian_filter(im, blur)
im2 = uint8(im2)
imNum = str(blur)
subplot(1, 4, 2 + bi)
axis('off')
title('标准差'+imNum, fontproperties=font)
imshow(im2)
show()