【问题标题】:Mutex and thread in videoCapturevideoCapture 中的互斥锁和线程
【发布时间】:2015-10-28 11:24:02
【问题描述】:

我已经使用工作线程实时获取最新帧,代码如下。但是在我的代码中,有一个问题。帧一直是第一帧,没有更新。结果第一帧做remap(),remap结果帧做下一个循环remap...不知道为什么frame没有更新。如果我删除线 remap() 或将此线替换为 dilate(frame, frame..) ,则框架会一直更新。另外,如果我将框架复制到图像并使用图像进行重映射(),框架可以更新。但是为什么在这种情况下框架无法更新。有人可以帮助我吗?谢谢。

std::mutex mtxCam;
void task(VideoCapture cap, Mat& frame) {
     while (true) {
         mtxCam.lock();
         cap >> frame;
         mtxCam.unlock();  
     }
}
int main() {
    Mat frame, image;
    VideoCapture cap;
    cap.open(0);
    cap.set(CV_CAP_PROP_FRAME_WIDTH, 1600);
    cap.set(CV_CAP_PROP_FRAME_HEIGHT, 1080);
    cap >> frame;
    thread t(task, cap, frame);
    while (true) {
       initUndistortRectifyMap(
        cameraMatrix,  // computed camera matrix
        distCoeffs,    // computed distortion matrix
        Mat(),     // optional rectification (none) 
        Mat(),     // camera matrix to generate undistorted
        Size(1920 * 1.3, 1080 * 1.3),
        //            image.size(),  // size of undistorted
        CV_32FC1,      // type of output map
        map1, map2);   // the x and y mapping functions
      mtxCam.lock();
      remap(frame, frame, map1, map2, cv::INTER_LINEAR);
      frame.copyTo(image);
      mtxCam.unlock();
      ...//image processing loop
    }
}

【问题讨论】:

  • 帽 >> 框架;尝试在 while 循环中使用它。!!
  • 这里我使用线程来获取框架。所以我认为我不需要将 cap >> 框架放在 while 循环中

标签: c++ multithreading opencv


【解决方案1】:

这里有两个问题:

1) 您传递一个帧,然后每次将视频捕获映射到同一帧,而不会在处理该帧后清除它。

2) 你需要一个信号机制(信号量),而不是一个锁定机制(互斥体)。

类似的东西:

while (true) {
         frame.clear();
         cap >> frame;
         semCam.Give();
     }

  semCam.Take();
  remap(frame, frame, map1, map2, cv::INTER_LINEAR);
  frame.copyTo(image);

您在这里处理的是生产者-消费者问题。 因此,线程 1 产生帧,线程 2 消耗帧进行图像处理。

线程 1 将帧插入队列,通知线程 2 帧已准备好进行处理,并等待线程 2 发出帧已处理完毕的信号。

算法:

线程 1

FrameProcessed.Wait()
FrameQueue.insert()
FrameQueueReadyForProcessing.Give()

线程 2

FrameQueueReadyForProcessing.Wait()
消费帧(FrameQueue.Pop()) FrameProcessed.Give()

不幸的是,C++11 没有开箱即用的信号量实现。 但是你可以自己滚动一个。

https://gist.github.com/yohhoy/2156481

【讨论】:

  • 感谢您的回答。但是 frame(Mat) 没有 claer() 功能。您能告诉我如何包含 semCam 吗?我找不到它
猜你喜欢
  • 2013-01-31
  • 2012-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-25
  • 1970-01-01
  • 1970-01-01
  • 2018-05-23
相关资源
最近更新 更多