【问题标题】:OpenCV with pthreads and mutexes带有 pthread 和互斥锁的 OpenCV
【发布时间】:2014-12-06 16:01:22
【问题描述】:

我编写了一个相当基本的 C++ 程序,它使用 OpenCV 库来显示我拥有的 IP 摄像机的视频流。

由于我以后想添加图像处理代码,我认为使用线程来做是个好主意。一个线程捕获最近的帧,另一个线程读取此帧并将其显示在屏幕上。我使用了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; 
}

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

【问题讨论】:

    标签: c++ multithreading opencv pthreads mutex


    【解决方案1】:

    我可以使用以下代码解决这个问题:

    #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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-05
      • 2013-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-20
      • 2015-06-19
      • 2017-11-21
      相关资源
      最近更新 更多