python+opencv 视频格式转换

我遇到一个视频,无法正常打开,常规软件无法转格式,直接上代码:

import cv2
from tqdm import tqdm


def main(video_path='test.mp4', out_path='test2.mp4'):  # 自定义输出后缀
    cap = cv2.VideoCapture(video_path)
    frame_cnt = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    weight = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    fps = int(cap.get(cv2.CAP_PROP_FPS))

    size = (weight, height)
    fourcc = cv2.VideoWriter_fourcc(*'XVID')
    out = cv2.VideoWriter(out_path, fourcc, fps, size)  # fourcc是编码格式,size是图片尺寸
    for n in tqdm(range(frame_cnt)):
        # print('视频合成进度:', n, frame_cnt)
        ret, frame = cap.read()
        # cv2.imshow('frame', frame)
        out.write(frame)
        if cv2.waitKey(10) & 0xFF == ord('q'):
            break

    cap.release()
    out.release()


if __name__ == "__main__":
    main()

 

posted @ 2022-03-17 14:49  牛郎  阅读(888)  评论(0编辑  收藏  举报