一、相关背景
把一个场视频切割成多个短视频,目前是切割成长度一直的短视频,可以自己按照需求更改
二、相关代码
import os
import os.path as osp
import cv2
import math
video_filename = '/home/testdata/test2.mov'
save_dir = '/home/testdata/split_test2/'
cap = cv2.VideoCapture(video_filename)
video_fps = int(cap.get(cv2.CAP_PROP_FPS))
video_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
frame_size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
fourcc = cv2.VideoWriter_fourcc('m','p','4','v')
dura_seconds = 50
dura_frames = dura_seconds * video_fps
print(f"This video will be split into {math.ceil(video_frames/dura_frames)} splits ")
is_success, bgr_im = cap.read()
frame_index = 1
split_video_fullname = osp.join(save_dir,f'{frame_index // dura_frames :>03d}.mov')
print(f'Write split {split_video_fullname}')
v = cv2.VideoWriter(split_video_fullname, fourcc, video_fps, frame_size)
v.write(bgr_im)
while True:
is_success, bgr_im = cap.read()
frame_index += 1
if not is_success:
cap.release()
v.release()
break
if ((frame_index % dura_frames) != 0):
if v.isOpened():
v.write(bgr_im)
if ((frame_index % dura_frames) == 0):
if v.isOpened():
v.write(bgr_im)
v.release()
split_video_fullname = osp.join(save_dir,f'{frame_index // dura_frames :>03d}.mov')
v = cv2.VideoWriter(split_video_fullname, fourcc, video_fps, frame_size)
print(f'Write split {split_video_fullname}')
cap.release()
|