我正在尝试使用OpenCV通过单独的线程工作者从多个摄像头捕获图像。
最终,CaptureWorker会将帧提供给工作队列进行处理,但目前我还想保存图像。以下代码运行,但保存的“#”框架'已损坏,无法打开,但不是空的。
最初,我在CaptureWorker :: startCapture()中构建和存储VideoCapture;但是,程序在打开流时崩溃了。在main()中构建和打开VideoCapture会打开相机并允许线程运行。
是什么导致帧写入中断?没有报告错误。
的main.cpp
int main(int argc, char * argv[]) {
if(argc <= 1) {
cout << "No camera arguments have been specified. Exiting." << endl;
return -1;
}
int numberOfCameras = argc - 1;
int cameraNumbers[argc-1];
for(int i=0; i<numberOfCameras; i++) {
cameraNumbers[i] = atoi(argv[i+1]);
}
VideoCapture cameras[10];
pthread_t cameraThreads[numberOfCameras];
for(int i=0; i<numberOfCameras; i++) {
cout << "Creating camera thread: " << i << endl;
cameras[i] = VideoCapture(i);
CaptureWorker capWorker(cameras[i], i);
pthread_create(&cameraThreads[i], NULL, &CaptureWorker::startCaptureWrap, &capWorker);
}
cout << "Closing Main" << endl;
pthread_exit(NULL);
}
CaptureWorker.cpp
class CaptureWorker {
private:
int cameraNumber;
string cameraName;
VideoCapture camera;
public:
CaptureWorker(VideoCapture camera, int cameraNumber) {
this->cameraNumber = cameraNumber;
this->camera = camera;
this->cameraName = "Camera_";
cameraName.append(to_string(cameraNumber));
cout << "CaptureWorker: Worker created" << endl;
}
void *startCapture(void) {
string imageSavePath = "Resources/images/" + this->cameraName;
mkdir(imageSavePath.c_str(), 0777);
cout << "CaptureWorker: Starting capture from camera" << endl;
int count = 0;
while(count <= 3) {
cout << "Capturing frame " << count;
Mat frame;
this->camera >> frame;
cout << " --- ";
string imageNameAndPath;
imageNameAndPath.append(imageSavePath);
imageNameAndPath.append("/img_");
imageNameAndPath.append(to_string(count).c_str());
imageNameAndPath.append(".jpg");
cout << "Saving to: " << imageNameAndPath.c_str() << endl;
imwrite(imageNameAndPath.c_str(), frame);
int c = cvWaitKey(1000);
if((char)c==27 ) {
break;
}
count++;
}
return 0;
}
static void *startCaptureWrap(void *arg) {
return ((CaptureWorker *) arg)->startCapture();
}
};
在OSX中使用eclipse中的交叉g ++编译器。免责声明:C ++,OpenCV,多线程的新手,希望我避免了一个愚蠢的错误。