关于python:pythonopenCV对视频进行截取

87次阅读

共计 1213 个字符,预计需要花费 4 分钟才能阅读完成。

应用 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

正文完
 0