你如何在pytorch中更改输入图片的尺寸? [英] How do you change the dimension of your input pictures in pytorch?

本文介绍了你如何在pytorch中更改输入图片的尺寸?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个卷积神经网络,我希望它拍摄输入图片和输出图片,但是当我将图片转换为张量时,它们的维度错误:

i made a convolutional nuralnetwork and i want it to take input pictures and output pictures but when i turn the pictures into tensors they have the wrong dimension :

RuntimeError: Expected 4-dimensional input for 4-dimensional weight [20, 3, 5, 5], but got 3-dimensional input of size [900, 1440, 3] instead 

如何更改图片的尺寸?为什么需要改变?以及如何使输出成为图片?我尝试使用

how do i change the dimension of the pictures ? and why does it need to be changed? and how do i make the output an picture? i tryed to use

transform = transforms.Compose(
[transforms.ToTensor(),
 transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])

对 img 进行规范化,但它没有改变尺寸.这是我的 nuralnet

to normilize the img but it didnt change the dimension . here is my nuralnet

    def __init__(self):
    super(Net, self).__init__()
    torch.nn.Module.dump_patches = True
    self.conv1 = nn.Conv2d(3, 20, 5)
    self.pool = nn.MaxPool2d(2, 2)
    self.conv2 = nn.Conv2d(20, 16, 5)
    self.fc1 = nn.Linear(16*5*5, 120)
    self.fc2 = nn.Linear(120, 84)
    self.fc3 = nn.Linear(84, 16*5*5)


def forward(self, x):
    x = self.pool(F.relu(self.conv1(x)))
    x = self.pool(F.relu(self.conv2(x)))
    x = x.view(-1, 16 * 5 )
    x = F.relu(self.fc1(x))
    x = F.relu(self.fc2(x))
    x = self.fc3(x)


    return x

在这里我得到图像并将其放入列表:

here i get the image and put it into a list:

for i in range(4):
l.append(ImageGrab.grab())

这是将 img 转换为张量的代码

and here is the code that turns the img into an tensor

k=torch.from_numpy(np.asarray(l[1],dtype="int32" ))

推荐答案

综上所述,根据你我发表的评论:

错误是由于 torch.nn 仅支持小批量.输入应采用 (batch_size, channels, height, width) 形式.您似乎缺少批次维度.您可以添加 .unsqueeze(0) 以在第一个位置添加一个假批量维度.

The error is due to torch.nn only supports mini-batches. The input should be in the form (batch_size, channels, height, width). You seem to be missing the batch dimension. You can add .unsqueeze(0) to add a fake batch dimension in the first position.

除上述之外,您还必须将图像的尺寸从 [HxWxC] 重新排列为 [CxHxW].这是通过 PyTorch 中的 .ToTensor() 转换完成的.

In addition to the above, you'll also have to rearrange the dimensions of your image from [HxWxC] to [CxHxW]. This is done by .ToTensor() transformation in PyTorch.

对于输入图像的大小不匹配问题,您可以使用如下转换:

For the size mismatch problem of your input image, you could use transformation like this:

transform = transforms.Compose(
                   [transforms.Resize((32,32)),
                    transforms.ToTensor(),
                    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])

这篇关于你如何在pytorch中更改输入图片的尺寸?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆