如果参数无效,cv2.VideoWriter
会将内容写入stderr。这里有一个最小的例子:
import cv2
cv2.VideoWriter("foo.mp4", cv2.VideoWriter_fourcc(*"mp4v"), 90000, (240, 240))
像这样运行
python3 video_verification/verification.py 2> err.txt
人们可以在err.txt
:中看到预期的错误
[mpeg4 @ 0x13e4640] timebase 1/90000 not supported by MPEG 4 standard, the maximum admitted value for the timebase denominator is 65535
[ERROR:0] global /tmp/pip-req-build-13uokl4r/opencv/modules/videoio/src/cap_ffmpeg_impl.hpp (2705) open Could not open codec mpeg4, error: Unspecified error
[ERROR:0] global /tmp/pip-req-build-13uokl4r/opencv/modules/videoio/src/cap_ffmpeg_impl.hpp (2722) open VIDEOIO/FFMPEG: Failed to initialize VideoWriter
然而,我无法在Python中直接捕捉到这一点。以下是我迄今为止的两次(失败的(尝试:
import io
from contextlib import redirect_stdout, redirect_stderr
import cv2
f_out = io.StringIO()
f_err = io.StringIO()
with redirect_stdout(f_out):
with redirect_stderr(f_err):
fps = 90000
writer = cv2.VideoWriter(
"foo.mp4", cv2.VideoWriter_fourcc(*"mp4v"),
fps, (240, 240)
)
print(f"stdout: {f_out.getvalue()}")
print(f"stderr: {f_err.getvalue()}")
import io
import sys
import cv2
def flush():
sys.stdout.flush()
sys.stderr.flush()
flush()
original_stdout = sys.stdout
original_stderr = sys.stderr
captured_stdout = io.StringIO()
captured_stderr = io.StringIO()
sys.stdout = captured_stdout
sys.stderr = captured_stderr
flush()
cv2.VideoWriter("foo.mp4", cv2.VideoWriter_fourcc(*"mp4v"), 90000, (240, 240))
flush()
sys.stdout = original_stdout
sys.stderr = original_stderr
print(f"stdout: {captured_stdout.getvalue()}")
print(f"stderr: {captured_stderr.getvalue()}")
我很想知道我做错了什么
我找到了wurlitzer库,它可以做到这一点,即捕获C库写入的流:
import cv2
from wurlitzer import pipes
with pipes() as (out, err):
cv2.VideoWriter("foo.mp4", cv2.VideoWriter_fourcc(*"mp4v"), 90000, (240, 240))
print(f"stderr: {err.read()}")