opencv-python对大视频切割成小视频

安装

 pip install opencv-python

读取视频,获取视频对象

# 获得视频对象  av_path <===> 视频地址
videoCapture = cv2.VideoCapture(av_path)
# 获得码率及尺寸
fps = videoCapture.get(cv2.CAP_PROP_FPS)
size = (int(videoCapture.get(cv2.CAP_PROP_FRAME_WIDTH)), int(videoCapture.get(cv2.CAP_PROP_FRAME_HEIGHT)))
fNUMS = videoCapture.get(cv2.CAP_PROP_FRAME_COUNT)
print('fps {}  size {} nums {}'.format(fps, size, fNUMS))

构建要存入的视频格式

fps = 20  # 保存视频的帧率 安装原来的一倍速度进行保存
size = (1280, 720)  # 保存视频的大小

name = 1
fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
vout_1 = cv2.VideoWriter('./av-d/output{}.mp4'.format(name), fourcc, fps, size)

循环读取将其保存到对应文件中

num = -1
five_t = 3 * 60  # 按照每3分钟保存成一个小视频
timeSpace = needTime = five_t * 20 # 每秒20帧

while videoCapture.isOpened():
    print("\r", "正在截取第{}个视频".format(name), end="", flush=True)
    num += 1
    success, frame = videoCapture.read()
    if success:
        if(num % timeSpace < needTime - 1):
            vout_1.write(frame)
        else:
            name += 1
            vout_1 = cv2.VideoWriter('./av-d/output{}.mp4'.format(name), fourcc, fps, size)
    else:
        break
print("end--------------------------->")
videoCapture.release()

备注 : VideoWriter_fourcc对象

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
    cv2.VideoWriter_fourcc('m', 'p', '4', 'v')    文件名后缀为.mp4

你可能感兴趣的:(python,opencv)