pytorch高斯函数自定义卷积核

1.直接输入参数

pytorch高斯函数自定义卷积核_第1张图片

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

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

参数:

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

 pytorch高斯函数自定义卷积核_第2张图片

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

dilation,groups)

pytorch高斯函数自定义卷积核_第3张图片

在一次卷积计算中,filter可以在input的两个维度上扫描,即参数stride的取值为一个元组,例如stride=(2, 3),即在hieght维度上的步长为2,在width上的步长为3。pytorch高斯函数自定义卷积核_第4张图片

 2.cv2自带

pytorch高斯函数自定义卷积核_第5张图片

 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()

你可能感兴趣的:(高斯模糊,pytorch,深度学习,python)