【opencv】opencv写视频不成功原因分析

0.环境

ubuntu20.04
opencv-python==4.1.2.30

1.代码

import cv2

path = "test.mp4"
save_path = "test_result.mp4"
vid_cap = cv2.VideoCapture(path)
fourcc = 'MJPG'  # output video codec
fps = vid_cap.get(cv2.CAP_PROP_FPS)
w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*fourcc), fps, (w, h))

ret_val, img = self.cap.read()
while ret_val
    if img is not None and ret_val:
        img = cv2.resize(img, (1080, 720))
    vid_writer.write(img)

vid_cap.release()
vid_writer.release()

2.原因

1)对应宽高不对

如果原始图像有经过了resize,vid_cap.get得到的是原始视频的w,h;那么w,h改变,vid_writer写视频失败。

2)fourcc 

另外有可能是视频编码方式问题,具体看:

python-opencv写入视频文件无法播放? - 知乎

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