I'm using OpenCV python to capture a video. This is my code
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
When a frame is not ready it produces an error like this
or
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
I wanted to find a way to hide this error! I guess that this error is being produced by ffmpeg
. Is there any way to hide or disable it?
This error is produced when I call cap.read()
. And I also tried to wrap it with try ... except ...
but it doesn't work because it doesn't throw any exceptions.
When using OpenCV and Python bindings, you’re bound to come across NoneType errors at some point. In my experience, over 95% of the time these NoneType errors can be traced back to either an issue with cv2.imread or cv2.VideoCapture . I have provided details for each of the cases below.
If you try to call the .read method of an instantiated cv2.VideoCapture (regardless if it’s a video file or webcam stream) and notice a NoneType error or AssertionError , then you likely have a problem with either: The path to your input video file (it’s probably incorrect).
I have provided details for each of the cases below. If you are receiving a NoneType error and your code is calling cv2.imread , then the likely cause of the error is an invalid file path supplied to cv2.imread .
A final, more rare problem you may encounter with cv2.imread is that your image does exist on disk, but you didn’t compile OpenCV with the given image I/O libraries installed. For example, let’s say you have a .JPEG file on disk and you knew you had the correct path to it.
One way to hide ffmpeg errors is by redirecting sterr elsewhere. I found this brilliant example on how to hide the errors.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With