RuntimeError: Given groups=1, weight of size [1, 1, 3, 3], expected input[1, 3, 1402, 1200] to have 1 channels, but got 3 channels instead
通过翻译得知这是 因为数据读入的通道不对,应该是1通道的,但是我们所得确是3通道的。通过查看读取的数据img的信息,发现mode是RGB。
但是我们需要的是一通道的灰度图,所以需要将mode模式改变一下。
原代码为:
o_tensor = ToTensor()
to_pil = ToPILImage()
input = to_tensor(img).unsqueeze(0)
kernel = t.ones(3,3)/-9
kernel[1][1] = 1
conv = nn.Conv2d(1,1,(3,3),3,bias=False)
conv.weight.data = kernel.view(1,1,3,3)
out = conv(V(input))
to_pil(out.data.squeeze(0))
错误:
RuntimeError: Given groups=1, weight of size [1, 1, 3, 3], expected input[1, 3, 1402, 1200] to have 1 channels, but got 3 channels instead
修改
o_tensor = ToTensor()
to_pil = ToPILImage()
img = Image.open('images/SDZ.jpeg')
if img.mode != 'L':
img = img.convert('L') #仅仅加上这两行就可以了
input = to_tensor(img).unsqueeze(0)
kernel = t.ones(3,3)/-9
kernel[1][1] = 1
conv = nn.Conv2d(1,1,(3,3),3,bias=False)
conv.weight.data = kernel.view(1,1,3,3)
out = conv(V(input))
to_pil(out.data.squeeze(0))
完成 !解决问题