视频指定片段截取

视频指定片段截取

今天写的一个小脚本,想指定时间段截取MP4文件

代码如下:

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

t1 = time.time()
filename = '../test.mp4'
capture = cv2.VideoCapture(filename)
if capture.isOpened() is False:
    print("Error opening the video file!")
    sys.exit()
frames = capture.get(cv2.CAP_PROP_FRAME_COUNT) #get all frames.
height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT)) #Width of the frames in the video stream.
width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH)) #Height of the frames in the video stream.
fps = capture.get(cv2.CAP_PROP_FPS) #Get frame rate.

# 创建保存视频文件类对象
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter('out_test.mp4', fourcc, fps,  (width, height))  # VideoWriter

# 计算视频的长度/s (基于需要,我截取的是倒数120s至倒数10s的片段)
video_length = frames / fps
start = video_length - 120
stop = video_length - 10

# 设置帧读取的起始位置
capture.set(cv2.CAP_PROP_POS_FRAMES, start * fps)
pos = capture.get(cv2.CAP_PROP_POS_FRAMES)  # 获得帧的位置
while (pos <= stop*fps):
    ret, frame = capture.read()  # 捕获帧的位置
    out.write(frame)   # 保存帧
    pos = capture.get(cv2.CAP_PROP_POS_FRAMES)
capture.release()
out.release()
total_time = time.time()-t1
print(f"单个视频截取已完成,用时{total_time} s!")

有几个需要注意的点

  1. MP4文件的解码格式要使用(*mp4v)
  2. cv2.videowriter函数时,高和宽作为元组时,一定是width在前,height在后。
  3. 基于capture.get,每次循环给定捕获帧的位置。较其它的判别读取指定片段用时更少。

[参考博文]((54条消息) python-opencv截取视频片段_可可爱爱的小肥肥的博客-CSDN博客)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

行人yuuu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值