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
import numpy as np from scipy import signal import matplotlib.pyplot as plt # Define 2D Gaussian kernel def gkern(kernlen=256, std=128): """Returns a 2D Gaussian kernel array.""" gkern1d = signal.gaussian(kernlen, std=std).reshape(kernlen, 1) gkern2d = np.outer(gkern1d, gkern1d) return gkern2d # Generate random matrix and multiply the kernel by it A = np.random.rand(256*256).reshape([256,256]) # Test plot plt.figure() plt.imshow(A*gkern(256, std=32)) plt.show()
The closest suggestion I found is based on this post:
import torch.nn as nn conv = nn.Conv2d(in_channels = 1, out_channels = 1, kernel_size=264, bias=False) with torch.no_grad(): conv.weight = gaussian_weights
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:
torchvision.transforms.GaussianBlur(kernel_size, sigma=(0.1, 2.0))
Check the documentation for more info