summaryrefslogtreecommitdiff
path: root/conv-pytorch.py
blob: b777c5339420e01a7b445e6e70701477a0af0cac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import torch
import torch.nn.functional as F
import matplotlib.pyplot as plt
from PIL import Image

img_pil = Image.open("./cameraman.png").convert("L") 
img_tensor = torch.tensor(list(img_pil.getdata()), dtype=torch.float32).reshape(1, 1, img_pil.height, img_pil.width) / 255.0

kernel = torch.tensor([[1., 0., -1.],
                       [2., 0., -2.],
                       [1., 0., -1.]])

weight = kernel.view(1, 1, 3, 3)

conv_result = F.conv2d(img_tensor, weight, padding=1)

plt.imshow(conv_result.squeeze().numpy(), cmap='gray')
plt.show()