使用cv2对视频进行切割
import cv2
def clip_video(source_video, target_video, start_time, end_time):
cap = cv2.VideoCapture(source_video)
if not cap.isOpened():
logger_warning('video is not opened')
else:
success, frame = cap.read()
f_shape = frame.shape
f_height = f_shape[0] # 原视频图片的高度
f_width = f_shape[1]
fps = cap.get(5) # 帧速率
frame_number = cap.get(7) # 视频文件的帧数
duration = frame_number / fps # 视频总帧数/帧速率 是时间/秒【总共有多少秒的视频时间】
if start_time > duration or end_time > duration:
return
start_time = fps * float(start_time)
end_time = fps * float(end_time)
# AVI格式编码输出 XVID
four_cc = cv2.VideoWriter_fourcc(*'H264')
video_writer = cv2.VideoWriter(target_video, four_cc, fps, (int(f_width), int(f_height)))
num = 0
while True:
success, frame = cap.read()
if int(start_time) <= int(num) <= int(end_time):
if success:
video_writer.write(frame)
else:
break
num += 1
if num > frame_number:
break
cap.release()
VideoWriter_fourcc编码格式:
fourcc意为四字符代码(Four-Character Codes),顾名思义,该编码由四个字符组成,下面是VideoWriter_fourcc对象一些常用的参数,注意:字符顺序不能弄混
cv2.VideoWriter_fourcc('I', '4', '2', '0'),该参数是YUV编码类型,文件名后缀为.avi
cv2.VideoWriter_fourcc('P', 'I', 'M', 'I'),该参数是MPEG-1编码类型,文件名后缀为.avi
cv2.VideoWriter_fourcc('X', 'V', 'I', 'D'),该参数是MPEG-4编码类型,文件名后缀为.avi
cv2.VideoWriter_fourcc('T', 'H', 'E', 'O'),该参数是Ogg Vorbis,文件名后缀为.ogv
cv2.VideoWriter_fourcc('F', 'L', 'V', '1'),该参数是Flash视频,文件名后缀为.flv
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。