2014-12-06 109 views
0

我已经写了一个相当基本的C++程序,它使用OpenCV库来显示我拥有的IP摄像头的视频流。使用pthreads和互斥体的OpenCV

因为我想在未来添加图像处理代码,所以我认为使用线程来完成它是个好主意。一个线程捕获最近的帧,另一个线程读取该帧并将其显示在屏幕上。我用pthread_mutex_t来锁定帧变量。

我的问题是代码实际上编译,但是当我执行程序时什么也没有发生,它只是在几秒钟后才存在。我已经验证这不是VideoCapture对象的问题,但我没有任何其他想法,为什么这不起作用。

这是我的代码:

#include <stdio.h> 
#include <opencv2/opencv.hpp> 
#include <iostream> 
#include <pthread.h> 

using namespace cv; 
using namespace std; 

//GLOBALS 
VideoCapture vcap; 
Mat frame; 
pthread_mutex_t *frameLocker; 

const string videoStreamAddress = "http://10.0.0.6/mjpg/video.mjpg"; 

void *Proc(void *arg) 
{ 
    for(;;) 
    { 
     pthread_mutex_lock(frameLocker); 
     vcap.read(frame); 
     pthread_mutex_unlock(frameLocker); 
    } 
} 

int main(int, char**) { 
    frameLocker = new pthread_mutex_t(); 
    vcap.open(videoStreamAddress); 

    pthread_mutex_init(frameLocker,NULL); 
    pthread_t *ProcThread; 
    pthread_create(ProcThread, NULL, Proc, NULL); 


    for(;;) 
    {    
     pthread_mutex_lock(frameLocker); 
     imshow("Output Window", frame);   
     pthread_mutex_unlock(frameLocker); 
    } 

    delete frameLocker; 
} 

我会很高兴,如果你能帮助我解决这个问题。 谢谢, 马坦

回答

3

我能解决这个使用下面的代码:

#include <stdio.h> 
#include <opencv2/opencv.hpp> 
#include <iostream> 
#include <pthread.h> 

using namespace cv; 
using namespace std; 

//GLOBALS 
VideoCapture vcap; 
Mat frame; 
pthread_mutex_t frameLocker; 

const string videoStreamAddress = "http://IP/mjpg/video.mjpg"; 

void *UpdateFrame(void *arg) 
{ 
    for(;;) 
    { 
     Mat tempFrame; 
     vcap >> tempFrame; 

     pthread_mutex_lock(&frameLocker); 
     frame = tempFrame; 
     pthread_mutex_unlock(&frameLocker); 
    } 
} 

int main(int, char**) { 
    vcap.open(videoStreamAddress); 

    pthread_mutex_init(&frameLocker,NULL); 
    pthread_t UpdThread;  
    pthread_create(&UpdThread, NULL, UpdateFrame, NULL); 


    for(;;) 
    { 
     Mat currentFrame; 
     pthread_mutex_lock(&frameLocker); 
     currentFrame = frame; 
     pthread_mutex_unlock(&frameLocker); 
     if(currentFrame.empty()){ 
      printf("recieved empty frame\n"); 
      continue; 

     } 


     imshow("Output Window", currentFrame); 
     waitKey(1); 
    } 
}