0

I’m new to Python and trying to do some manipulations with filters in PyTorch.

I’m struggling re how to apply a Conv2d. I’ve got the following code which creates a 3x3 moving average filter:

resized_image4D = np.reshape(image_noisy, (1, 1, image_noisy.shape[0], image_noisy.shape[1]))
t = torch.from_numpy(resized_image4D)

conv = torch.nn.Conv2d(in_channels=1, out_channels=1, kernel_size=3, padding=1, bias=False)
conv.weight = torch.nn.Parameter(torch.ones((1,1,3, 3))/9.0)

Normally in NumPy I’d just call filtered_image = convolve2d(image, kernel), but I’ve not been able to figure out what the PyTorch equivalent is after days of searching.

Ivan
  • 34,531
  • 8
  • 55
  • 100

1 Answers1

1

I think you are looking for torch.nn.functional.conv2d.

Hence, your snippets becomes:

resized_image4D = np.reshape(image_noisy, (1, 1, image_noisy.shape[0], image_noisy.shape[1]))
t = torch.from_numpy(resized_image4D)

conv = torch.nn.functional.conv2d(in_channels=1, out_channels=1, kernel_size=3, padding=1, bias=False)
conv.weight = torch.nn.Parameter(torch.ones((1,1,3, 3))/9.0)
ndrwnaguib
  • 5,623
  • 3
  • 28
  • 51