opencv多线程处理数据

单线程处理数据,需要阻塞等待处理完一张图片才开始处理下一张图片。

这里想用多线程的思路来处理。

需要注意的是,imshow只能在主线程里面调用,具体原因还未查清楚~~

下面是代码:

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp> 
#include <iostream>
#include <queue>
  
boost::mutex io_mutex;  
using namespace cv; 
using namespace std;
Mat image_catch;
volatile bool thread_all_exit = false;
Mat display_mat_origin;
Mat display_mat_process;
void catch_image()
{
  Mat frame; 
  VideoCapture capture(0);
  if(!capture.isOpened()){
        boost::mutex::scoped_lock lock(io_mutex);   
        cout<<"fail to open!"<<endl;
        thread_all_exit = true;  
        return;
  }   
   while(1){
        capture.read(frame);
        if (frame.empty())
        {   
           capture.release();   
           thread_all_exit = true;          
           break;
        }   
        resize(frame,frame,Size(640,480),0,0,CV_INTER_LINEAR);
        boost::mutex::scoped_lock lock(io_mutex);
        image_catch=frame.clone();
        display_mat_origin =frame.clone();
        if(thread_all_exit){
          capture.release();   
          break;
        }   
   }   
  capture.release();   
}
void process_image()  
{  
    Mat img;  
    while (1){
        if (!image_catch.empty())
        {   
          boost::mutex::scoped_lock lock(io_mutex);
          img = image_catch.clone();
          resize(img,img,Size(320,240),0,0,CV_INTER_LINEAR);
          display_mat_process =img.clone();        
if(thread_all_exit){
              break;
         }
      }  
    }     
}  

int main(int argc, char* argv[])  
{  
  boost::thread thread_catch_img(boost::bind(&catch_image));  
  boost::thread thread_process_img(boost::bind(&process_image));
  while(1){
    if (!display_mat_origin.empty())
    {
        boost::mutex::scoped_lock lock(io_mutex);
        imshow("data",display_mat_origin);
        imshow("process",display_mat_process);
        if (waitKey(1)==27 || thread_all_exit)
        {
          thread_all_exit = true;
          break;
        }
    }
    if (!display_mat_process.empty())
    {
        boost::mutex::scoped_lock lock(io_mutex);
        imshow("process",display_mat_process);
        if (waitKey(1)==27||thread_all_exit)
        {
          thread_all_exit = true;
          break;
        }
    }
  }
  thread_catch_img.join();  
  thread_process_img.join();  
  return 0;  
}  

下面是makefile文件:

CC=g++
BOOSTLIB=-L/usr/local/lib \
         -lboost_system  -lboost_thread-mt 
INC=$(shell pkg-config --cflags opencv) 
LIB=$(shell pkg-config --libs opencv)
SRCFILE=$(wildcard *.cc)
DEBUGFLG=
all:
        $(CC) $(SRCFILE) $(DEBUGFLG) $(INC) $(BOOSTLIB) $(LIB) -o out
clean:
        rm -rf out




评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值