Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

OpenCV C++ Multithreading

I made a opencv c++ program that does a lot of image processing on frames from a video feed and as such decided to implement multithreading to speed things up. However, because I am new to opencv and multithreading, my implementation has caused my image processing functions to produce erroneous results. My guess is that the thread in which image processing occurs cannot keep up with the thread that reads in each frame. Here is my code:

void CaptureFrames() {
  VideoCapture capture(0);
  if (!capture.isOpened()) {
    cout << "cannot open camera" << endl;
  }

  while (true) {
    //CAMERAFRAME is a global Mat defined at the top of my program
    capture.read(CAMERAFRAME);
   }
  }

void ProcessFrames() {

  while (true) {



  Mat hsvFrame;
  Mat binMat;
  Mat grayFrame;
  Mat grayBinMat;

  if (!CAMERAFRAME.empty()) {
    //do image processing functions (these worked before implementing threads and are not causing errors)

    imshow("gray binary", grayBinMat);
    imshow("multithread test", CAMERAFRAME);
}



if (waitKey(1) >= 0) { break; }
 }
}

int main(int argc, char** argv[]) {
  thread t1(CaptureFrames);
  thread t2(ProcessFrames);

  while(true) {
    if(waitKey(1) >= 0) {break;}
  }

  return 0;
}

Any ideas on what I am doing wrong?