我有几个视频,我将它们逐帧加载到一个numpy数组中。例如,如果我有8个视频,它们将转换为8维numpy数组,其中每个内部数组根据各个视频的帧数具有不同的维数。当我打印
array.shape
我的输出是(8,)
现在,我想为此数据创建一个数据加载器,为此,我想将此numpy数组转换为割炬张量。但是,当我尝试使用torch.from_numpy
甚至只是torch.tensor
函数对其进行转换时,都会出现错误
TypeError: can't convert np.ndarray of type numpy.object_. The only supported types are: float64, float32, float16, int64, int32, int16, int8, uint8, and bool.
我认为这是因为我的内部数组大小不同。一种可能的解决方案是人为地为我的视频添加一个尺寸,以使其具有相同的尺寸,然后使用np.stack
,但这可能会在以后导致问题。有更好的解决方案吗?
编辑:实际上添加尺寸是行不通的,因为np.stack要求所有尺寸都相同。
编辑:示例数组将类似于:
[ [1,2,3], [1,2], [1,2,3,4] ]
这被存储为(3,)形状的np数组。实际的数组实际上是4维的(帧数x高度x宽度x通道),因此这只是一个示例。
答案 0 :(得分:1)
您可以使用rnn
实用程序功能pad_sequence
使它们的大小相同。
ary
array([list([1, 2, 3]), list([1, 2]), list([1, 2, 3, 4])], dtype=object)
from torch.nn.utils.rnn import pad_sequence
t = pad_sequence([torch.tensor(x) for x in ary], batch_first=True)
t
tensor([[1, 2, 3, 0],
[1, 2, 0, 0],
[1, 2, 3, 4]])
t.shape
torch.Size([3, 4])