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

查看:3898
本文介绍了如何在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天全站免登陆