卷积神经网络——灰度图像的卷积

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

一、前提介绍:

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

如上图所示:最左侧矩阵是一个灰度图像,中间是一个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()

结果:

 

 

  • 3
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值