I am looking for a way to apply a Gaussian filter to an image (tensor) only using PyTorch functions. Using numpy, the equivalent code is
JavaScript
x
19
19
1
import numpy as np
2
from scipy import signal
3
import matplotlib.pyplot as plt
4
5
# Define 2D Gaussian kernel
6
def gkern(kernlen=256, std=128):
7
"""Returns a 2D Gaussian kernel array."""
8
gkern1d = signal.gaussian(kernlen, std=std).reshape(kernlen, 1)
9
gkern2d = np.outer(gkern1d, gkern1d)
10
return gkern2d
11
12
# Generate random matrix and multiply the kernel by it
13
A = np.random.rand(256*256).reshape([256,256])
14
15
# Test plot
16
plt.figure()
17
plt.imshow(A*gkern(256, std=32))
18
plt.show()
19
The closest suggestion I found is based on this post:
JavaScript
1
6
1
import torch.nn as nn
2
3
conv = nn.Conv2d(in_channels = 1, out_channels = 1, kernel_size=264, bias=False)
4
with torch.no_grad():
5
conv.weight = gaussian_weights
6
But it gives me the error NameError: name 'gaussian_weights' is not defined
. How can I make it work?
Advertisement
Answer
There is a Pytorch class to apply Gaussian Blur to your image:
JavaScript
1
2
1
torchvision.transforms.GaussianBlur(kernel_size, sigma=(0.1, 2.0))
2
Check the documentation for more info