pytorch高斯函数自定义卷积核

1.直接输入参数

np.repeat()用于将numpy数组重复。

numpy.repeat(a, repeats, axis=None);

参数:

axis=0,沿着y轴复制,实际上增加了行数
axis=1,沿着x轴复制,实际上增加了列数

 

 torch.nn.functional.conv2d(input,filters,bias,stride,padding,

dilation,groups)

在一次卷积计算中,filter可以在input的两个维度上扫描,即参数stride的取值为一个元组,例如stride=(2, 3),即在hieght维度上的步长为2,在width上的步长为3。

 2.cv2自带

 3.公式(可以改变半径r和方差)

import torch
import numpy as np
import math
import matplotlib.pyplot as plt


class MyGaussianBlur():
    #初始化
    def __init__(self, radius=1, sigema=1.5):
        self.radius=radius
        self.sigema=sigema
    #高斯的计算公式
    def calc(self,x,y):
        res1=1/(2*math.pi*self.sigema*self.sigema)
        res2=math.exp(-(x*x+y*y)/(2*self.sigema*self.sigema))
        return res1*res2

    #滤波模板
    def template(self):
        sideLength=self.radius*2+1
        result=np.zeros((sideLength, sideLength))
        for i in range(0, sideLength):
            for j in range(0,sideLength):
                result[i, j] = self.calc(i - self.radius, j - self.radius)
        all= result.sum()
        return result/all
    #滤波函数
    def filter(self, image, template):
        kernel = np.array(template)
        kernel2 = torch.FloatTensor(kernel).expand(3, 1, 2*r+1, 2*r+1)
        weight = torch.nn.Parameter(data=kernel2, requires_grad=False)
        new_pic2 = torch.nn.functional.conv2d(image, weight, padding=1, groups=3)
        return new_pic2


r=4 #模版半径,自己自由调整
s=5 #sigema数值,自己自由调整
GBlur=MyGaussianBlur(radius=r, sigema=s)#声明高斯模糊类
temp=GBlur.template()#得到滤波模版
pic = plt.imread("1.jpg")
tensor_pic=torch.tensor(pic,dtype=torch.float32)/255
im=tensor_pic.permute(2,0,1).unsqueeze(0)

image=GBlur.filter(im, temp)#高斯模糊滤波,得到新的图片
print(image.shape)

plt.imshow(image.squeeze(0).permute(1,2,0))
plt.show()

MNIST数据集的高斯模糊

import numpy as np
import torch
import torchvision.transforms as transforms
from torchvision import datasets
from torch.utils.data import DataLoader
import matplotlib.pyplot as plt
import torch.nn.functional as F
import math

transform = transforms.ToTensor()

train_data = datasets.MNIST(root='mnist', train=True, transform=transform, download=True)
test_data = datasets.MNIST(root='mnist', train=False, transform=transform, download=True)

batch_size = 64
num_worker = 0

train_loader = DataLoader(dataset=test_data, batch_size=batch_size, shuffle=True, num_workers=num_worker)
test_loder = DataLoader(dataset=test_data, batch_size=batch_size, shuffle=False, num_workers=num_worker)

dataiters = iter(test_loder)
images, labels = dataiters.next()


class MyGaussianBlur():
    # 初始化
    def __init__(self, radius=1, sigema=1.5):
        self.radius = radius
        self.sigema = sigema

    # 高斯的计算公式
    def calc(self, x, y):
        res1 = 1 / (2 * math.pi * self.sigema * self.sigema)
        res2 = math.exp(-(x * x + y * y) / (2 * self.sigema * self.sigema))
        return res1 * res2

    # 滤波模板
    def template(self):
        sideLength = self.radius * 2 + 1
        result = np.zeros((sideLength, sideLength))
        for i in range(0, sideLength):
            for j in range(0, sideLength):
                result[i, j] = self.calc(i - self.radius, j - self.radius)
        all = result.sum()
        return result / all

    # 滤波函数
    def filter(self, image, template):
        kernel = np.array(template)
        kernel2 = torch.FloatTensor(kernel).expand(channel, 1, 2 * r + 1, 2 * r + 1)
        weight = torch.nn.Parameter(data=kernel2, requires_grad=False)
        new_pic2 = torch.nn.functional.conv2d(image, weight, padding=(2 * r + 1) // 2, groups=channel)
        return new_pic2


channel = 1  # 单通道为1, 三通道为3
r = 2  # 模版半径,自己自由调整
s = 5  # sigema数值,自己自由调整
GBlur = MyGaussianBlur(radius=r, sigema=s)  # 声明高斯模糊类
temp = GBlur.template()  # 得到滤波模版
image = GBlur.filter(images, temp)  # 高斯模糊滤波,得到新的图片

new_image = image.numpy()

times = 0
for i in range(4):
    times += 1
    print('count:', times)
    img = np.squeeze(new_image[i])  # 获得第一个图片的数
    # print('img:', img)
    print(new_image.shape)
    print(new_image[i].shape)

    print('shape', img.shape)
    plt.imshow(img, cmap='gray')
    plt.show()

  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值