《2019/06/06》python实现图像卷积运算

使用Python及numpy实现图像卷积运算

# @date 2019/06/06
# @desc 实现卷积

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
        w = kernel.shape[1] // 2

        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

    res = np.zeros((res_h, res_w), np.uint8)

    for i in range(res_h):
        for j in range(res_w):
            res[i, j] = normal(image[i:i+h_kernel, j:j+w_kernel], kernel)

    return res


def normal(image, kernel):
    res = np.multiply(image, kernel).sum()
    if res > 255:
        return 255
    else:
        return res


if __name__ == '__main__':
    path = r'E:\lhcz\images\me.jpg'
    image = cv2.imread(path)
    kernel = np.array([
        [-1, -1, 0],
        [-1, 0, 1],
        [0, 1, 1]
    ])
    res = conv(image, kernel, 'fill')
    plt.imshow(res), plt.show()
  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值