c++ - 带有 pthreads 和 mutexes 的 OpenCV

标签 c++ multithreading opencv pthreads mutex

我编写了一个相当基本的 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; 
}

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

最佳答案

我能够使用以下代码解决此问题:

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

关于c++ - 带有 pthreads 和 mutexes 的 OpenCV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27333498/

相关文章:

c++ - 操作系统信号处理循环 - 阻塞或非阻塞读取?

opencv - 使用 ffmpeg、OpenCV 的硬件加速 h264 解码

opencv - haarcascade_frontalface_default.xml在什么数据集上受训?

c++ - 如何禁用QT中的最大化按钮?

c++ - 函数修改未引用的类

c++ - 如何计算 double/float C++ 中的位数

c++ - 附加两个数组的最快方法(连接两个数组)C++

multithreading - 这个Delphi Thread代码正确吗?

java - 如何从另一个线程暂停和恢复 Java 中的线程

python - OpenCV-Tensorflow模型导入错误