Pytroch:实现几种常用的滤波器(高斯滤波 + 边缘检测)

卷积核(滤波器)及其特征映射

在这里插入图片描述

github地址

代码github地址

代码

# 介绍几种常用的卷积核
import torch
import torch.nn as nn
import matplotlib.pyplot as plt
import cv2
import numpy as np


img = cv2.imread('picture.jpg')
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img0 = np.array(img).reshape(img.shape[0], img.shape[1], 1)
img = np.transpose(img0, (2, 0, 1))
img = img[np.newaxis, :]
inp = torch.Tensor(img)
# 三种常见的卷积核
conv1 = nn.Conv2d(1, 1, (3, 3))
conv2 = nn.Conv2d(1, 1, (3, 3))
conv3 = nn.Conv2d(1, 1, (3, 3))

# 高斯滤波
w1 = torch.Tensor(np.array([[1/16, 1/8, 1/16], [1/8, 1/4, 1/8], [1/16, 1/8, 1/16]]).reshape(1, 1, 3, 3))
# 边缘检测1
w2 = torch.Tensor(np.array([[0, 1, 0], [1, -4, 1], [0, 1, 0]]).reshape(1, 1, 3, 3))
# 边缘检测2
w3 = torch.Tensor(np.array([[0, 1, 1], [-1, 0, 1], [-1, -1, 0]]).reshape(1, 1, 3, 3))
conv1.weight = nn.Parameter(w1)
conv2.weight = nn.Parameter(w2)
conv3.weight = nn.Parameter(w3)

out1 = conv1(inp).detach().numpy()
out2 = conv2(inp).detach().numpy()
out3 = conv3(inp).detach().numpy()
out1 = np.transpose(out1, (0, 2, 3, 1))
out2 = np.transpose(out2, (0, 2, 3, 1))
out3 = np.transpose(out3, (0, 2, 3, 1))

# 显示
plt.figure(figsize=(10, 5))
plt.subplot(141)
plt.imshow(img0.squeeze(), cmap="gray")
plt.subplot(142)
plt.imshow(out1.squeeze(), cmap='gray')
plt.subplot(143)
plt.imshow(out2.squeeze(), cmap='gray')
plt.subplot(144)
plt.imshow(out3.squeeze(), cmap='gray')
plt.show()

效果

在这里插入图片描述

  • 9
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值