【问题标题】:Pytorch can't convert np.ndarray of type numpy.objectPytorch 无法转换 numpy.object 类型的 np.ndarray
【发布时间】:2020-09-17 20:59:47
【问题描述】:

我正在尝试创建一个具有可变图像大小的 PyTorch 数据加载器。这是我的代码的 sn-p

def get_imgs(path_to_imgs):

    imgs = []
    for path in path_to_imgs:

        imgs.append(cv2.imread(path))

    imgs = np.asarray(imgs)    

    return imgs   

上面的函数接受一个路径列表并将图像从路径加载到列表'imgs'。顺便说一句,图像大小不相等。该列表看起来像 imgs = [NumPy 数组,NumPy 数组 ....]。但是,当我将列表转换为 np.asarray 时,它会将列表转换为 dtype = object。

这是我的数据加载器类

class Dataset(torch.utils.data.Dataset):

  def __init__(self, path_to_imgs, path_to_label):
        'Initialization'
        self.path_to_imgs = path_to_imgs
        self.path_to_label = path_to_label

        self.imgs = get_imgs(path_to_imgs)
        self.label = get_pts(path_to_label)

        self.imgs = torch.Tensor(self.imgs)             **Error here
        # self.imgs = torch.from_numpy(self.imgs)       ** I tried this as well. Same error

        self.label = torch.Tensor(self.label)

        self.len = len(self.imgs)

  def __len__(self):
        'Denotes the total number of samples'
        return self.len

  def __getitem__(self, index):

        return self.imgs, self.label

当我尝试将图像列表转换为张量**时,它失败并给出以下错误

无法转换 numpy.object_ 类型的 np.ndarray。唯一支持的类型是:float64、float32、float16、int64、int32、int16、int8、uint8 和 bool。

我看过herehere 类似的问题,但它们没有帮助。

【问题讨论】:

    标签: python-3.x pytorch classification


    【解决方案1】:
    def get_imgs(path_to_imgs): 图像 = [] path_to_imgs 中的路径: imgs.append(torch.Tensor(cv2.imread(path))) 返回图片 类数据集(torch.utils.data.Dataset): def __init__(self, path_to_imgs, path_to_label): '初始化' self.path_to_imgs = path_to_imgs self.path_to_label = path_to_label self.imgs = get_imgs(path_to_imgs) self.label = get_pts(path_to_label) # 填充操作 (https://pytorch.org/docs/stable/nn.html#padding-layers) # 用于 self.imgs 中的 img: # ... self.label = torch.Tensor(self.label) self.len = len(self.imgs) def __len__(self): '表示样本总数' 返回 self.len def __getitem__(self, index): 返回 self.imgs, self.label

    【讨论】:

    • 所以大小不等导致了问题?你能详细说明一下吗
    • @FarshidRayhan 在numpytorch 中都不能从不同形状的张量列表中创建一个张量。 numpy 创建一个对象数组。但是torch 无法将对象转换为浮点张量。因此,我们将图像保存为get_imgs 函数中的张量。现在,要从张量列表中创建一个张量,您需要填充它们。
    猜你喜欢
    • 2019-10-05
    • 2019-09-07
    • 2020-07-06
    • 2019-11-10
    • 2022-06-30
    • 1970-01-01
    • 2020-05-31
    • 2022-08-08
    • 2022-08-05
    相关资源
    最近更新 更多