Killing cv2 read process after N time

My guess is that the read() call is blocked somewhere inside C code. The signal handler runs, puts an exception into the Python interpreter somewhere, but the exception isn’t handled until the Python interpreter regains control. This is a limitation documented in the signal module:

A long-running calculation implemented purely in C (such as regular expression matching on a large body of text) may run uninterrupted for an arbitrary amount of time, regardless of any signals received. The Python signal handlers will be called when the calculation finishes.

One possible workaround is to read frames on a separate process using the multiprocessing module, and return them to the main process using a multiprocessing.Queue (from which you can get with a timeout). However, there will be extra overhead in sending the frames between processes.

Another approach might be to try and avoid the root of the problem. OpenCV has different video backends (V4L, GStreamer, ffmpeg, …); one of them might work where another doesn’t. Using the second argument to the VideoCapture constructor, you can indicate a preference for which backend to use:

cv.VideoCapture(..., cv.CAP_FFMPEG)

See the documentation for the full list of backends. Depending on your platform and OpenCV build, not all of them will be available.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top