如何使用 Python 解码库按时间戳而不是按帧索引查找?

问题描述

Decord 允许使用索引从文件中查找视频帧,例如:

video_reader = decord.VideoReader(video_path)
frames = video_reader.get_batch(indices)

如果我有时间戳(以秒为单位),我该怎么做?

解决方法

您可以获取每一帧的时间戳(平均其开始和结束时间),然后找到最接近的:

from typing import Sequence,Union

import decord
import numpy as np


def time_to_indices(video_reader: decord.VideoReader,time: Union[float,Sequence[float]]) -> np.ndarray:
    times = video_reader.get_frame_timestamp(range(len(video_reader))).mean(-1)
    indices = np.searchsorted(times,time)
    # Use `np.bitwise_or` so it works both with scalars and numpy arrays.
    return np.where(np.bitwise_or(indices == 0,times[indices] - time <= time - times[indices - 1]),indices,indices - 1)

frames = video_reader.get_batch(time_to_indices(indices))

注意 VideoReader C 对象(不是 Python 对象)已经加载了初始化时的所有帧时间戳。我们利用了它们应该被排序的事实。