一、前提介绍:
卷积在图像处理中经常被用于平滑、模糊、锐化、去噪、边缘取等工作中。图像处理中的卷积操作,其实就是利用卷积核(模板)在目标图像上滑动,将图像上的像素点依次对应到卷积核的中间像素处,每个像素点对齐后将图像上的像素灰度值与卷积核对应位置上的数值相乘,然后将相乘后的所有值相加,相加的结果作为当前像素的灰度值,并最终滑动完所有图像像素点的过程。

如上图所示:最左侧矩阵是一个灰度图像,中间是一个3*3的小矩阵,称为“卷积核”或“过滤器”。
1.导包
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
2. 过程:
#图像的卷积运算
#输入参数
# image:原图像
# mfilter:滤波器
#输出参数
# convImage:卷积后的图像
3.定义卷积函数:
def ImageConvolution( image, mfilter ):
mI, nI = np.shape( image )
[mF, nF] = np.shape( mfilter )
halfHeight = int( mF / 2 )
halfWidht = int( nF / 2 )
convImage = np.zeros( (mI, nI) )#卷积图像
#根据滤波器长度奇偶性的不同调整扩充图像的范围
if mF % 2 == 0:
imData = np.pad( image, (halfWidht, halfWidht-1), 'constant' )
else:
imData = np.pad( image, (halfWidht, halfHeight), 'constant' )
padmI, padnI = imData.shape
convHeight = padmI - mF + 1
convWidth = padnI - nF + 1
#依次截取与滤波器大小相同的图像块进行内积运算
for i in range( convHeight ):
for j in range( convWidth ):
localImage = imData[ i:i+mF, j:j+nF ]
convImage[i][j] = np.sum( localImage * mfilter )
convImage1 = convImage.clip( 0, 255 )
return convImage1
4.根据滤波器对图像进行卷积
filter1 = [ [-1, -2, -1], [0, 0, 0], [1, 2, 1] ]
imageConv = ImageConvolution( img, filter1 )
plt.figure( 'filter1' )
plt.imshow( imageConv, cmap = 'gray' )
plt.axis( 'off' )
filter2 = [ [1, -1], [1, -1] ]
imageConv = ImageConvolution( img, filter2 )
plt.figure( 'filter2' )
plt.imshow( imageConv, cmap = 'gray' )
plt.axis( 'off' )
filter3 = [ [-1, 1, 1, -1], [-1, 1, 1, -1], [-1, 1, 1, -1], [-1, 1, 1, -1] ]
imageConv = ImageConvolution( img, filter3 )
plt.figure( 'filter3' )
plt.imshow( imageConv, cmap = 'gray' )
plt.axis( 'off' )
if __name__ == '__main__':
main()
结果:




该博客介绍了如何使用Python进行图像的卷积运算。通过导入PIL、numpy和matplotlib库,定义一个卷积函数ImageConvolution,该函数接受原图像和滤波器作为输入,输出卷积后的图像。博客展示了3种不同的滤波器(边缘增强、平均滤波和锐化滤波)对图像进行卷积的效果。


1042

被折叠的 条评论
为什么被折叠?



