pytorch 自定义核进行卷积操作

1.介绍

    高斯滤波的用处很多,也有很多现成的包可以被调用,比如opencv里面的cv2.GaussianBlur,一般情况,我们是没必要去造轮子,除非遇到特殊情况,比如我们在使用pytorch的过程中,需要自定义高斯核进行卷积操作,假设,我们要用的高斯核的参数是以下数目:

0.006559650.013303730.006559650.000786330.00002292
0.006559650.054721570.110981640.054721570.00655965
0.013303730.110981640.225083520.110981640.01330373
0.006559650.054721570.110981640.054721570.00655965
0.000786330.006559650.013303730.006559650.00078633

    在使用pytorch过程中,常用的卷积函数是:

class torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True)
 
 

    感觉是无法自定义卷积权重,那么我们就此放弃吗?肯定不是,当你再仔细看看pytorch的说明书之后,会发现一个好东西:

torch.nn.functional.conv2d(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1)
 
 

    里面的weight参数刚好可以用高斯核参数来填充。

 

2.代码


 
 
  1. import torch
  2. import torch.nn as nn
  3. import torch.nn.functional as F
  4. from torch.autograd import Variable
  5. import numpy as np
  6. import cv2
  7. class GaussianBlurConv(nn.Module):
  8. def __init__(self, channels=3):
  9. super(GaussianBlurConv, self).__init__()
  10. self.channels = channels
  11. kernel = [[ 0.00078633, 0.00655965, 0.01330373, 0.00655965, 0.00078633],
  12. [ 0.00655965, 0.05472157, 0.11098164, 0.05472157, 0.00655965],
  13. [ 0.01330373, 0.11098164, 0.22508352, 0.11098164, 0.01330373],
  14. [ 0.00655965, 0.05472157, 0.11098164, 0.05472157, 0.00655965],
  15. [ 0.00078633, 0.00655965, 0.01330373, 0.00655965, 0.00078633]]
  16. kernel = torch.FloatTensor(kernel).unsqueeze( 0).unsqueeze( 0)
  17. kernel = np.repeat(kernel, self.channels, axis= 0)
  18. self.weight = nn.Parameter(data=kernel, requires_grad= False)
  19. def __call__(self, x):
  20. x = F.conv2d(x.unsqueeze( 0), self.weight, padding= 2, groups=self.channels)
  21. return x
  22. input_x = cv2.imread( "kodim04.png")
  23. cv2.imshow( "input_x", input_x)
  24. input_x = Variable(torch.from_numpy(input_x.astype(np.float32))).permute( 2, 0, 1)
  25. gaussian_conv = GaussianBlurConv()
  26. out_x = gaussian_conv(input_x)
  27. out_x = out_x.squeeze( 0).permute( 1, 2, 0).data.numpy().astype(np.uint8)
  28. cv2.imshow( "out_x", out_x)
  29. cv2.waitKey( 0)

    原图:

    输出图:

 

3.扩展应用

    我们知道了怎么自定义高斯核,其它的核都可以照搬,这里就不一一讲述了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
自定义卷积核并执行卷积操作,需要按照以下步骤进行: 1. 导入必要的库,包括PyTorch库和numpy库。 ```python import torch import numpy as np ``` 2. 定义卷积核的权重矩阵,可以手动创建或使用随机数生成器。然后将权重矩阵转换为PyTorch张量,以便在下一步中使用。 ```python kernel = np.array([[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]]).astype(np.float32) weights = torch.from_numpy(kernel).unsqueeze(0).unsqueeze(0) ``` 3. 创建输入张量,将其转换为PyTorch张量,并使用unsqueeze函数将其扩展为4D张量。 ```python input_tensor = np.random.rand(1, 1, 5, 5).astype(np.float32) input = torch.from_numpy(input_tensor).unsqueeze(0) ``` 4. 使用PyTorch中的conv2d函数进行卷积操作。将输入张量和权重矩阵传递给该函数,并指定所需的卷积参数(如步长、边界填充和输出通道数)。 ```python output = torch.nn.functional.conv2d(input, weights, stride=1, padding=0) ``` 5. 输出结果。可以使用PyTorch张量的numpy函数将张量转换为同类型的numpy数组,并使用它来输出卷积操作的结果。 ```python result = output.numpy() print(result) ``` 完整的示例代码如下所示: ```python import torch import numpy as np # 定义卷积核 kernel = np.array([[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]]).astype(np.float32) # 将卷积核转换为PyTorch张量 weights = torch.from_numpy(kernel).unsqueeze(0).unsqueeze(0) # 创建输入张量 input_tensor = np.random.rand(1, 1, 5, 5).astype(np.float32) # 将输入张量转换为PyTorch张量并扩展为4D张量 input = torch.from_numpy(input_tensor).unsqueeze(0) # 执行卷积运算 output = torch.nn.functional.conv2d(input, weights, stride=1, padding=0) # 输出结果 result = output.numpy() print(result) ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值