【问题标题】:inputing numpy array images into pytorch neural net将 numpy 数组图像输入 pytorch 神经网络
【发布时间】:2019-05-15 01:54:27
【问题描述】:

我有一个图像的 numpy 数组表示,我想把它变成一个张量,这样我就可以通过我的 pytorch 神经网络提供它。

我知道神经网络接受变换后的张量,这些张量不是排列在 [100,100,3] 而是 [3,100,100] 中,并且像素会重新缩放,并且图像必须是分批的。

所以我做了以下事情:

import cv2
my_img = cv2.imread('testset/img0.png')
my_img.shape #reuturns [100,100,3] a 3 channel image with 100x100 resolution
my_img = np.transpose(my_img,(2,0,1))
my_img.shape #returns [3,100,100] 
#convert the numpy array to tensor
my_img_tensor = torch.from_numpy(my_img)
#rescale to be [0,1] like the data it was trained on by default 
my_img_tensor *= (1/255)
#turn the tensor into a batch of size 1
my_img_tensor = my_img_tensor.unsqueeze(0)
#send image to gpu 
my_img_tensor.to(device)
#put forward through my neural network.
net(my_img_tensor)

但是这会返回错误:

RuntimeError: _thnn_conv2d_forward is not implemented for type torch.ByteTensor

【问题讨论】:

    标签: python numpy pytorch tensor


    【解决方案1】:

    问题是您提供给网络的输入是 ByteTensor 类型,而类似 conv 的操作只实现了浮点操作。试试下面的

    my_img_tensor = my_img_tensor.type('torch.DoubleTensor')
    # for converting to double tensor
    

    来源PyTorch Discussion Forum

    感谢AlbanD

    【讨论】:

    • 它实际上是 FloatTensor,但谢谢你,你的评论让我找到了答案。
    猜你喜欢
    • 2021-03-09
    • 1970-01-01
    • 1970-01-01
    • 2011-01-06
    • 2018-12-16
    • 2017-09-16
    • 1970-01-01
    • 2015-06-24
    • 2022-01-18
    相关资源
    最近更新 更多