RuntimeError: Given groups=1, weight of size [1, 1, 3, 3], expected input[1, 3, 1402, 1200] to have

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))

完成 !解决问题

解决链接来源:
https://www.codeleading.com/article/31383072717/

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值