我不是 TensorFlow 人,所以我的回答不会涵盖这一点,抱歉。
由于利用了数据中的时间相关性,视频格式通常会以更长的随机访问时间为代价来获得压缩。这是有道理的,因为人们通常按顺序访问视频帧,但如果您的访问完全是随机的,我建议您转换为 hdf5。否则,如果您访问视频的子序列,则保留视频格式可能是有意义的。
PyTorch 对视频 AFAIK 没有任何“有福”的方法,但我使用 imageio 来读取视频并寻找特定帧。一个简短的包装器使其遵循 PyTorch Dataset API。该代码相当简单,但有一个警告,这是允许将其与多处理 DataLoader 一起使用所必需的。
import imageio, torch
class VideoDataset:
def __init__(self, path):
self.path = path
# explained in __getitem__
self._reader = None
reader = imageio.get_reader(self.path, 'ffmpeg')
self._length = reader.get_length()
def __getitem__(self, ix):
# Below is a workaround to allow using `VideoDataset` with
# `torch.utils.data.DataLoader` in multiprocessing mode.
# `DataLoader` sends copies of the `VideoDataset` object across
# processes, which sometimes leads to bugs, as `imageio.Reader`
# does not support being serialized. Since our `__init__` set
# `self._reader` to None, it is safe to serialize a
# freshly-initialized `VideoDataset` and then, thanks to the if
# below, `self._reader` gets initialized independently in each
# worker thread.
if self._reader is None:
self._reader = imageio.get_reader(self.path, 'ffmpeg')
# this is a numpy ndarray in [h, w, channel] format
frame = self._reader.get_data(ix)
# PyTorch standard layout [channel, h, w]
return torch.from_numpy(frame.transpose(2, 0, 1))
def __len__(self):
return self.length
此代码可以调整为支持多个视频文件以及输出您想要的标签。