4

I'm trying to use OpenCV to open a camera. This works fine when I open the camera in the main thread, but when I try to open the camera while in a Boost thread, it fails. I haven't been able to google why this happens. I assume it's somehow related to the permissions of the Boost thread.

The following works fine:

#include <cv.h>
#include <boost/thread.hpp>
#include <highgui.h>

using namespace cv;
void openCamera() {
    Ptr< VideoCapture > capPtr(new VideoCapture(0)); // open the default camera
}

int main() {
    openCamera();
}

And my camera turns on briefly after which I get the message "Cleaned up camera" as one would expect.

But when I try the same through a Boost thread, it doesn't open the camera:

#include <cv.h>
#include <boost/thread.hpp>
#include <highgui.h>
#include <iostream>

using namespace cv;
void openCamera() {
    std::cout << "confirming that openCamera() was called" << std::endl;
    Ptr< VideoCapture > capPtr(new VideoCapture(0)); // open the default camera
}

int main() {
    boost::thread trackerThread( boost::bind(openCamera) );
}

This prints "confirming that openCamera() was called", but the camera never turns on and there is no "Cleaned up camera" message.

Is there any way I can fix it?

Thanks!

okintheory
  • 195
  • 1
  • 6
  • iirc The OpenCV Camera functions on mac require access to an objective-c `NSRunLoop`; don't know how to get at one from a new thread though. – James Mar 08 '11 at 00:20
  • How does that work? Could I pass a handle of some kind when creating the thread? – okintheory Mar 12 '11 at 11:43
  • I don't know. I think the problem is that NSRunLoop uses thread local storage --- so you need to create a new one for each thread that is going to use frameworks that depend on it to process events. – James Mar 12 '11 at 11:51

1 Answers1

7

I don't use boost a lot, but don't you need to do something to keep main() from exiting while your thread works? Like maybe...

int main() {
    boost::thread trackerThread( boost::bind(openCamera) );
    trackerThread.join();
}
bob2
  • 1,092
  • 9
  • 18
  • 2
    +1 Exactly. The thread is being create and main() is returning destroying the newly created thread. Well spotted. – karlphillip May 12 '11 at 16:21