python 使用ffmpeg随机提取视频中的一帧

环境

windows 环境下,需要安装以下库

在这里插入图片描述
还需要安装ffmpeg, 如果出现错误可以参考这篇博客

代码

import numpy as np
import cv2
import random
import os
import sys
import time
import ffmpeg


def read_frame_by_time(in_file, time):
    """
    指定时间节点读取任意帧
    """
    out, err = (
        ffmpeg.input(in_file, ss=time)
              .output('pipe:', vframes=1, format='image2', vcodec='mjpeg')
              .run(capture_stdout=True)
    )
    return out

def get_video_info(in_file):
    """
    获取视频基本信息
    """
    try:

        # cap = cv2.VideoCapture(in_file)
        # while (cap.isOpened()):
        #     ret, frame = cap.read()
        #     cv2.imshow('image', frame)
        #     k = cv2.waitKey(20)
        #     # q键退出
        #     if (k & 0xff == ord('q')):
        #         break
        #
        # cap.release()
        # cv2.destroyAllWindows()


        probe = ffmpeg.probe(in_file)
        video_stream = next((stream for stream in probe['streams'] if stream['codec_type'] == 'video'), None)
        if video_stream is None:
            print('No video stream found', file=sys.stderr)
            sys.exit(1)
        return video_stream
    except ffmpeg.Error as err:
        print(str(err.stderr, encoding='gbk'))
        sys.exit(1)




if __name__ == '__main__':
    # video_to_image()
    filename = "./test.mp4"
    
    # 读取视频的时长
    video_info = get_video_info(filename)
    total_duration = video_info['duration']
    # 随机选择一个时间
    random_time = random.uniform(0,float(total_duration))
    
    # 提取图片
    out = read_frame_by_time(filename, random_time)
    image_array = np.asarray(bytearray(out), dtype="uint8")
    img_frame = cv2.imdecode(image_array, cv2.IMREAD_COLOR)
    # 显示图片
    cv2.imshow('result.jpg',img_frame)
    cv2.waitKey(0)
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值