TLDR; 我的问题是如何从 TFRecords 加载压缩视频帧。
我正在建立一个数据管道,用于在大型视频数据集 ( Kinetics ) 上训练深度学习模型。为此,我正在使用 TensorFlow,更具体地说是tf.data.Dataset
和TFRecordDataset
结构。由于数据集包含约 30 万个 10 秒的视频,因此需要处理大量数据。在训练期间,我想从视频中随机采样 64 个连续帧,因此快速随机采样很重要。为了实现这一点,在训练期间可能会出现许多数据加载场景:
- 来自视频的样本。
ffmpeg
使用orOpenCV
和示例帧加载视频。不理想,因为在视频中搜索很棘手,并且解码视频流比解码 JPG 慢得多。 - JPG 图片。通过将所有视频帧提取为 JPG 来预处理数据集。这会生成大量文件,由于随机访问,这可能不会很快。
- 数据容器。将数据集预处理为
TFRecords
或HDF5
文件。需要做更多的工作来准备好管道,但很可能是这些选项中最快的。
我决定选择选项(3)并使用TFRecord
文件来存储数据集的预处理版本。然而,这也并不像看起来那么简单,例如:
- 压缩。将视频帧作为未压缩字节数据存储在 TFRecords 中将需要大量磁盘空间。因此,我提取所有视频帧,应用 JPG 压缩并将压缩字节存储为 TFRecords。
- 视频数据。我们正在处理视频,因此 TFRecords 文件中的每个示例都将非常大,并且包含多个视频帧(通常 250-300 用于 10 秒的视频,具体取决于帧速率)。
我编写了以下代码来预处理视频数据集并将视频帧写入 TFRecord 文件(每个文件大小约为 5GB):
def _int64_feature(value):
"""Wrapper for inserting int64 features into Example proto."""
if not isinstance(value, list):
value = [value]
return tf.train.Feature(int64_list=tf.train.Int64List(value=value))
def _bytes_feature(value):
"""Wrapper for inserting bytes features into Example proto."""
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
with tf.python_io.TFRecordWriter(output_file) as writer:
# Read and resize all video frames, np.uint8 of size [N,H,W,3]
frames = ...
features = {}
features['num_frames'] = _int64_feature(frames.shape[0])
features['height'] = _int64_feature(frames.shape[1])
features['width'] = _int64_feature(frames.shape[2])
features['channels'] = _int64_feature(frames.shape[3])
features['class_label'] = _int64_feature(example['class_id'])
features['class_text'] = _bytes_feature(tf.compat.as_bytes(example['class_label']))
features['filename'] = _bytes_feature(tf.compat.as_bytes(example['video_id']))
# Compress the frames using JPG and store in as bytes in:
# 'frames/000001', 'frames/000002', ...
for i in range(len(frames)):
ret, buffer = cv2.imencode(".jpg", frames[i])
features["frames/{:04d}".format(i)] = _bytes_feature(tf.compat.as_bytes(buffer.tobytes()))
tfrecord_example = tf.train.Example(features=tf.train.Features(feature=features))
writer.write(tfrecord_example.SerializeToString())
这很好用;数据集很好地编写为 TFRecord 文件,帧为压缩的 JPG 字节。我的问题是,如何在训练期间读取 TFRecord 文件,从视频中随机采样 64 帧并解码 JPG 图像。
根据TensorFlow 的文档,tf.Data
我们需要执行以下操作:
filenames = tf.placeholder(tf.string, shape=[None])
dataset = tf.data.TFRecordDataset(filenames)
dataset = dataset.map(...) # Parse the record into tensors.
dataset = dataset.repeat() # Repeat the input indefinitely.
dataset = dataset.batch(32)
iterator = dataset.make_initializable_iterator()
training_filenames = ["/var/data/file1.tfrecord", "/var/data/file2.tfrecord"]
sess.run(iterator.initializer, feed_dict={filenames: training_filenames})
有很多关于如何使用图像执行此操作的示例,这非常简单。但是,对于视频和帧的随机采样,我被卡住了。该tf.train.Features
对象将帧存储为frame/00001
等frame/000002
。我的第一个问题是如何从dataset.map()
函数内部随机采样一组连续帧?考虑因素是由于 JPG 压缩,每个帧都有可变数量的字节,需要使用tf.image.decode_jpeg
.
任何帮助如何最好地设置从 TFRecord 文件读取视频样本将不胜感激!