使用opencv但输出文件的视频写入无法播放

问题描述 投票:1回答:1

我想并排使用两个视频来编写视频文件,但最后输出文件无法在任何视频播放器中播放。这是我的代码:

from __future__ import print_function
import numpy as np
import argparse
import cv2
import tkinter as tk
from tkinter import filedialog
import os
import os.path

ap = argparse.ArgumentParser()
ap.add_argument("-o", "--output", type=str, default="sample.avi",
            help="path to output video file")
ap.add_argument("-f", "--fps", type=int, default=100.0,
            help="FPS of output video")
ap.add_argument("-c", "--codec", type=str, default="MJPG",
            help="codec of output video")
args = vars(ap.parse_args())

root = tk.Tk()
root.withdraw()

source_video = filedialog.askopenfilename(title="Select file")
sign = filedialog.askopenfilename(title="Select file")
print("[INFO] Capturing video...")
cap1 = cv2.VideoCapture(source_video)
cap2 = cv2.VideoCapture(sign)

fourcc = cv2.VideoWriter_fourcc(*args["codec"])
writer = None
(h, w) = (None, None)
zeros = None
i = 0 
try:
    while cap1.isOpened():
        ret, frame1 = cap1.read()
        if ret:
            frame1 = cv2.resize(frame1, (0, 0), fx=0.5, fy=0.5)
            (h, w) = frame1.shape[:2]

            ret, frame2 = cap2.read()
            if ret:
                frame2 = cv2.resize(frame2, (w, h))

        else:
            break

        if writer is None:
            writer = cv2.VideoWriter(args["output"], fourcc, args["fps"], 
(h, w*2), True)
            zeros = np.zeros((h, w*2), dtype="uint8")
        output = np.zeros((h, w*2, 3), dtype="uint8")

        if frame2 is None:
            output[0:h, 0:w] = frame1
            writer.write(output)
        else:
            output[0:h, 0:w] = frame1
            output[0:h, w:w * 2] = frame2
            writer.write(output)

        cv2.imshow('output', output)
        if cv2.waitKey(25) & 0xFF == ord('q'):
            break

    writer.release()
    cv2.destroyAllWindows()


except Exception as e:
        print(str(e))

我没有得到任何错误所有的事情进展顺利,但当我尝试播放目录中的输出视频文件时,它将无法播放。我也检查文件大小约16KB。我不知道问题出在哪里。请帮我。我正在使用:Windows 10 64位Python3.7 Pycharm作为IDE

python-3.x opencv video-capture
1个回答
1
投票

frameSizeVideoWriter参数是(宽度,高度),它有点隐藏在文档中(例如,here)。所以在你的代码中,它应该是

writer = cv2.VideoWriter(args["output"], fourcc, args["fps"], (w*2, h), True)

完成此修复后,您的代码为我制作了工作视频。

我注意到你的代码从输入视频“学习”帧大小而不是帧率,但我认为这是故意的。

© www.soinside.com 2019 - 2024. All rights reserved.