如何在使用OpenCV(python)时隐藏/禁用ffmpeg错误?

时间:2013-09-29 20:20:32

标签: python opencv error-handling ffmpeg

我正在使用OpenCV python来捕获视频。 这是我的代码

import cv2

cap = cv2.VideoCapture("vid.mp4")
while True:
    flag, frame =  cap.read()

    if not flag:
        cv2.imshow('video', frame)

    if cv2.waitKey(10) == 27:
        break

当帧未准备好时,会产生类似

的错误

enter image description here

Truncating packet of size 2916 to 1536
[h264 @ 0x7ffa4180be00] AVC: nal size 2912
[h264 @ 0x7ffa4180be00] AVC: nal size 2912
[h264 @ 0x7ffa4180be00] no frame!

[mov,mp4,m4a,3gp,3g2,mj2 @ 0x7ffa41803000] stream 0, offset 0x14565: partial file

我想找到隐藏此错误的方法!我猜这个错误是由ffmpeg产生的。有没有办法隐藏或禁用它?

当我致电cap.read()时会产生此错误。我还尝试用try ... except ...包装它,但它不起作用,因为它不会抛出任何异常。

1 个答案:

答案 0 :(得分:0)

隐藏ffmpeg错误的一种方法是将sterr重定向到其他地方。我发现this brilliant example关于如何隐藏错误。

import ctypes
import io
import os
import sys
import tempfile
from contextlib import contextmanager

import cv2

libc = ctypes.CDLL(None)
c_stderr = ctypes.c_void_p.in_dll(libc, 'stderr')


@contextmanager
def stderr_redirector(stream):
    original_stderr_fd = sys.stderr.fileno()

    def _redirect_stderr(to_fd):
        libc.fflush(c_stderr)
        sys.stderr.close()
        os.dup2(to_fd, original_stderr_fd)
        sys.stderr = io.TextIOWrapper(os.fdopen(original_stderr_fd, 'wb'))

    saved_stderr_fd = os.dup(original_stderr_fd)
    try:
        tfile = tempfile.TemporaryFile(mode='w+b')
        _redirect_stderr(tfile.fileno())
        yield
        _redirect_stderr(saved_stderr_fd)
        tfile.flush()
        tfile.seek(0, io.SEEK_SET)
        stream.write(tfile.read().decode())
    finally:
        tfile.close()
        os.close(saved_stderr_fd)

f = io.StringIO()
with stderr_redirector(f):
    # YOUR CODE HERE

f.close()