简体   繁体   中英

How to actually apply a Conv2d filter in Pytorch

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM