微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何使用 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 对象)已经加载了初始化时的所有帧时间戳。我们利用了它们应该被排序的事实。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。