cv::VideoCapture: accessing the same webcam from two threads

1.2k Views Asked by At

I have two classes with two threads: One displays the webcam frames in my GUI, One records a video from the same webcam. I'm using a different cv::VideoCapture in each class to access my webcam. Both consturctors for my MainWindow and Recorder class have the line theWebcam.open(INDEX) to open the webcam. My problem is that about 50% of the time my program crashes on start when it tries to open the second cv::VideoCapture object. How can I use the same webcam in both classes?

2

There are 2 best solutions below

2
On

As far as I know it is not possible (but never tried by myself). I prefer following approach:

One thread "communicates" with the camera, i.e. grabs images, and sends one copy to a thread to write to a file and one copy to the gui to show a live image.

Moreover, as long as a camera wouldn't support multicasting (assuming it's an ip-camera) the framerate will most likely drop.

0
On

I have had success with the technique Robert was describing as well. I use pointers to pass images around to different threads and let the main thread create all the VideoCapture objects I need and the namedWindow objects as well. I am now speaking outside of my area of expertise, but my experience suggests that VideoCapture and namedWindow objects from OpenCV can not be created in any thread aside from the main thread, and must instead be passes into secondary threads.