今天写的一个小脚本,想指定时间段截取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!")
有几个需要注意的点
[参考博文]((54条消息) python-opencv截取视频片段_可可爱爱的小肥肥的博客-CSDN博客)