import torch as t
from torch import nn
from PIL import Image
from torchvision.transforms import ToTensor,ToPILImage
from matplotlib import pyplot as plt
to_tensor = ToTensor() # img 转换成 Tensor
to_pil = ToPILImage()
lena = Image.open('E:\lena\lena512.bmp')
input = to_tensor(lena).unsqueeze(0)
"""
如果想输入一个数据,而不是一个batch,必须调用squeeze(0)函数将数据伪装成batch_size=1的batch
"""
kernel = t.ones(3, 3)/-9
kernel[1][1] = 1
conv = nn.Conv2d(1, 1, (3, 3), 1, bias = False)
"""
torch.nn.Conv2d(in_channels, out_channels, kernel_size,stride =1,padding=0,dilation=1,groups=1,bias=True)
in_channel:输入信号的通道
out_channel:卷积产生的通道
bigotimes:表示相关系数的计算
dilation:用于控制内核点之间的距离
groups:从输入通道到输出通道的阻塞连接数
bias:偏置
"""
conv.weight.data = kernel.view(1,1,3,3)
"""
weight(tensor)--卷积的权重,大小是(out_channels,in_channels,kernel_size
"""
out = conv(input)
to_pil(out.data.squeeze(0))
结果