python+numpy+cv2实现图片卷积运算代码详细注解

"""   
@Project Name: CNN featuremap
@Author: milanboy
@Time: 2019-06-27, 09:37
@Python Version: python3.6
@Coding Scheme: utf-8
@Interpreter Name: PyCharm
"""
import numpy as np
import cv2
from matplotlib import pyplot as plt


def conv(image, kernel, mode='same'):

    if mode == 'fill':  #选择是否进行边缘填充
        h = kernel.shape[0] // 2   #卷积核的列除以2取整
        w = kernel.shape[1] // 2   #卷积核的行除以2取整
        #在原始图像边缘进行填充,常数填充,填数值0,假设原始图像600*600,卷积核大小5*5,则填充后图像大小604*604
        image = np.pad(image, ((h, h), (w, w), (0, 0)), 'constant')  

    #进行卷积运算
    conv_b = _convolve(image[:, :, 0], kernel)
    conv_g = _convolve(image[:, :, 1], kernel)
    conv_r = _convolve(image[:, :, 2], kernel)
    res = np.dstack([conv_b, conv_g, conv_r])
    return res


def _convolve(image, kernel):
    h_kernel, w_kernel = kernel.shape  #获取卷积核的长宽,也就是行数和列数

    h_image, w_image = image.shape   #获取欲处理图片的长宽

    #计算卷积核中心点开始运动的点,因为图片边缘不能为空
    res_h = h_image - h_kernel + 1
    res_w = w_image - w_kernel + 1

    #生成一个0矩阵,用于保存处理后的图片
    res = np.zeros((res_h, res_w), np.uint8)

    for i in range(res_h):   #行
        for j in range(res_w):   #列
            #image处传入的是一个与卷积核一样大小矩阵,这个矩阵取自于欲处理图片的一部分
            #这个矩阵与卷核进行运算,用i与j来进行卷积核滑动
            res[i, j] = normal(image[i:i + h_kernel, j:j + w_kernel], kernel) 

    return res

def normal(image, kernel):
    #np.multiply()函数:数组和矩阵对应位置相乘,输出与相乘数组/矩阵的大小一致(点对点相乘)
    
    res = np.multiply(image, kernel).sum() #点对点相乘后进行累加
    if res > 255:
        return 255
    elif res<0:
        return 0
    else:
        return res
if __name__ == '__main__':
    path = './img/1.jpg'      # 原图像路径
    image = cv2.imread(path)


    #kernel1 是一个3x3的边缘特征提取器,可以提取各个方向上的边缘
    #kernel2 是一个5x5的浮雕特征提取器。

    kernel1 = np.array([
        [1, 1, 1],
        [1, -7.5, 1],
        [1, 1, 1]
    ])
    kernel2 = np.array([[-1, -1, -1, -1, 0],
                        [-1, -1, -1, 0, 1],
                        [-1, -1, 0, 1, 1],
                        [-1, 0, 1, 1, 1],
                        [0, 1, 1, 1, 1]])
    res = conv(image, kernel2, 'same')
    plt.axis('off')    #画图不显示坐标轴
    plt.imshow(res)
    plt.savefig('./out/filtered_picdoramon01.jpg', dpi=600)
    plt.show()

参考文献:https://blog.csdn.net/weixin_40769885/article/details/93872654

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

六五酥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值