You need to enable JavaScript to run this app. 如何基于TimeseriesGenerator从大视频逐帧构建LSTM时序训练数据集
优惠活动
大模型
产品
解决方案
定价
更多

如何基于TimeseriesGenerator从大视频逐帧构建LSTM时序训练数据集

报错根因

tf.keras.preprocessing.sequence.TimeseriesGenerator 设计上面向已加载到内存的数组对象,会直接对传入数据执行 data[start:end:step] 格式的切片操作批量取数。你当前自定义Video类的__getitem__方法仅处理整数帧号索引,遇到slice类型的切片参数时没有做分支兼容,直接将slice对象传入moviepy的get_frame方法,最终触发类型不匹配的报错。
此外TimeseriesGenerator默认输出为“输入长序列、预测序列末尾对应的单步值”的格式,和你需要的“输入1秒帧序列、预测后续整1秒帧序列”的多对多需求不匹配,更适合自定义符合Keras规范的惰性时序生成器,在不一次性加载全视频的前提下生成目标格式的训练样本。

实现步骤

1. 补全自定义Video类的切片索引兼容能力

在现有Video类中修改__getitem__方法,同时支持整数单帧索引、slice批量索引两种取值场景,完成边界裁剪和参数默认值处理,保证切片读帧的稳定性:

def __getitem__(self, frame_idx):
    total_frames = len(self)
    # 处理整数索引场景(单帧提取)
    if isinstance(frame_idx, int):
        if frame_idx < 0:
            frame_idx = total_frames + frame_idx
        frame_time = frame_idx / self.video.fps
        return self.video.get_frame(frame_time)
    # 处理切片索引场景(批量帧提取)
    elif isinstance(frame_idx, slice):
        # 解析切片参数,补全默认值
        start = frame_idx.start if frame_idx.start is not None else 0
        stop = frame_idx.stop if frame_idx.stop is not None else total_frames
        step = frame_idx.step if frame_idx.step is not None else 1
        # 边界裁剪,避免帧号越界
        start = max(0, min(start, total_frames))
        stop = max(0, min(stop, total_frames))
        # 遍历读取切片范围内的所有帧,堆叠为numpy数组
        frame_list = list(range(start, stop, step))
        frames = [self[fi] for fi in frame_list]
        return np.stack(frames, axis=0)
    else:
        raise TypeError(f"不支持的索引类型:{type(frame_idx)}")

修改完成后,你可以直接通过切片操作批量读帧,比如HENRY[0:60:2]就会返回从0帧开始、每2帧抽1个、到60帧结束的序列帧数组,和TimeseriesGenerator的索引调用逻辑完全兼容。

2. 自定义匹配需求的Keras时序生成器

基于TensorFlow官方的Sequence接口实现惰性生成器,完全贴合你需要的样本格式:

  • 样本结构:以每2帧抽1帧的采样率,输入为连续30帧的抽帧序列(对应1秒时长的覆盖范围),目标为输入序列后紧跟的连续30帧抽帧序列
  • 内存友好:仅在读取batch时按需加载对应帧,不会一次性将全视频读入内存,适配普通PC的硬件限制
  • 兼容性:可直接传入model.fit()接口,支持多进程加载、自动shuffle等训练特性

生成器核心代码如下:

from tensorflow.keras.utils import Sequence

class VideoFrameSequenceGenerator(Sequence):
    def __init__(self, video, sampling_step=2, input_seq_len=30, output_seq_len=30, sample_stride=30, batch_size=4):
        """
        超大视频惰性时序样本生成器
        :param video: 自定义Video类实例
        :param sampling_step: 单帧抽取间隔
        :param input_seq_len: 输入序列的抽帧数量
        :param output_seq_len: 目标序列的抽帧数量
        :param sample_stride: 相邻样本的滑动步长
        :param batch_size: 单批次样本量
        """
        self.video = video
        self.sampling_step = sampling_step
        self.input_seq_len = input_seq_len
        self.output_seq_len = output_seq_len
        self.sample_stride = sample_stride
        self.batch_size = batch_size
        # 计算合法总样本数,保证帧号不越界
        total_frames = len(video)
        required_frames = (input_seq_len + output_seq_len) * sampling_step
        self.total_samples = (total_frames - required_frames) // (sample_stride * sampling_step) + 1

    def __len__(self):
        # 每个epoch的batch总数量
        return int(np.ceil(self.total_samples / self.batch_size))

    def __getitem__(self, batch_idx):
        # 定位当前batch包含的样本范围
        batch_start = batch_idx * self.batch_size
        batch_end = min((batch_idx + 1) * self.batch_size, self.total_samples)
        batch_X, batch_y = [], []
        for sample_idx in range(batch_start, batch_end):
            # 计算当前样本的起始帧号
            start_frame = sample_idx * self.sample_stride * self.sampling_step
            # 读取输入序列
            X_seq = self.video[
                start_frame : start_frame + self.input_seq_len * self.sampling_step : self.sampling_step
            ]
            # 读取目标序列
            y_start = start_frame + self.input_seq_len * self.sampling_step
            y_seq = self.video[
                y_start : y_start + self.output_seq_len * self.sampling_step : self.sampling_step
            ]
            batch_X.append(X_seq)
            batch_y.append(y_seq)
        return np.array(batch_X), np.array(batch_y)

3. 生成器调用与验证

按照你的需求参数初始化生成器,提取第一个batch即可验证样本结构:

# 初始化生成器
fps = 30
train_gen = VideoFrameSequenceGenerator(
    video=HENRY,
    sampling_step=2,
    input_seq_len=30,
    output_seq_len=30,
    sample_stride=30,
    batch_size=4
)
# 提取第一个batch验证
X, y = train_gen[0]

最终生成的第一个样本的帧号完全匹配你预期的格式:

  • X序列包含的帧:0, 2, 4, ..., 58,共30个抽帧
  • y序列包含的帧:60, 62, 64, ..., 118,共30个抽帧

可直接传入多对多LSTM模型完成训练。如果单帧分辨率较高、内存压力大,可以在生成器的__getitem__方法中增加帧缩放、像素值归一化的预处理步骤,进一步降低内存占用。

内容的提问来源于stack exchange,提问作者gokdumano

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.27 16:15:04