Applying a Conv2d filter to an image tensor

Hey guys,

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 avg 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 np I’d just call convolve2x(image,kernel), but I’ve not been able to figure out what the PyTorch equivalent is after days of searching.

Apologies if a dumb question. Any pointers in the right direction would be greatly appreciated.

Thank you very much

You could use torch.nn.functional.conv2d then you can pass the input image right into the conv2d layer. Here is the documentation.

Got it, managed to get it to work. Thank you very much!!!