0

I have written a simple motion capture and recording script in Python 3. I am on cv2 version 4.4.0, installed on Ubuntu using "apt install python3-opencv". My script connects to an IP camera, fetching the URL from a config file. When a host at a URL isn't reachable, I raise an exception, output a message on the command line, and wait 30 seconds. However, even when catching this error, OpenCV spits out an error on the terminal. I really don't want to see this error, as I want the terminal to be a clean experience for the user. How can I successfully catch and suppress this error message?

My full code is here on Github.

while True:
      try:
          video=cv2.VideoCapture(camera_url)
          if video is None or not video.isOpened():
            raise ConnectionError
          size=(int(video.get(3)), int(video.get(4)))
          check, frame = video.read()

...

except ConnectionError:
          print("Retrying connection to ",camera_name," in ",str(reconnect_time), " seconds...")
          time.sleep(reconnect_time)

The error message I would like:

Retrying connection to  front_yard  in  30  seconds...

The error message I get:

[tcp @ 0x18d4b40] Connection to tcp://192.168.1.102:8000 failed: No route to host
[ERROR:0] global /tmp/pip-req-build-99ib2vsi/opencv/modules/videoio/src/cap.cpp (140) open VIDEOIO(CV_IMAGES): raised OpenCV exception:

OpenCV(4.4.0) /tmp/pip-req-build-99ib2vsi/opencv/modules/videoio/src/cap_images.cpp:253: error: (-5:Bad argument) CAP_IMAGES: can't find starting number (in the name of file): http://192.168.1.102:8000/stream.mjpg in function 'icvExtractPattern'


Retrying connection to  front_yard  in  30  seconds...
  • Try this, and if it works then this means it's not Python throwing the error. `import sys; sys.stderr = open('/dev/null', 'w')`. You can also try the python 3.5 solution https://stackoverflow.com/questions/1956142/how-to-redirect-stderr-in-python – thethiny Feb 26 '21 at 20:59
  • I think you're barking up the right tree. I didn't see any result from adding that code. But when I ran "export OPENCV_LOG_LEVEL=OFF" in my terminal, most of the error message no longer shows up. Now it gives the bit about the [tcp @ 0x...] part and then my exception message. I've not seen a Python package do something like this before. – phriskiii Feb 26 '21 at 21:33
  • It's not a python package. It's a Shell SubProcess that's being called by OpenCV. It's a C++ compiled application that gets called to execute commands. What you need is to turn off error by OpenCV. https://stackoverflow.com/questions/49602465/how-to-stop-opencv-error-message-from-printing-in-python – thethiny Feb 26 '21 at 21:59
  • That makes sense. Thank you for sharing. "export OPENCV_LOG_LEVEL=OFF" on Linux did the trick. – phriskiii Feb 27 '21 at 02:57

0 Answers0