opencv切割视频:把长视频切割成固定时间的短视频

一、相关背景

把一个场视频切割成多个短视频,目前是切割成长度一直的短视频,可以自己按照需求更改

二、相关代码

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')

# duration of every split ( second)
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

# Create handle of split
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

    # Break when no more frame
    if not is_success:
        cap.release()
        v.release()
        break
    
    # Write frame to split
    if ((frame_index % dura_frames) != 0):
        if v.isOpened():
            v.write(bgr_im)

    # If there is the and of the split, 
    # 1. write the final frame , 2. then close the split handle, 3. create next cap handle
    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()



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值