Home > Software engineering >  OpenCV for C : Passing matrix using std::ref() gives a 0x0 dimension matrix
OpenCV for C : Passing matrix using std::ref() gives a 0x0 dimension matrix

Time:06-30

this is my code snippet:

for(int i = 0; i < numT; i  ) {
    cv::Mat m2 = m1(cv::Range(get<0>(offsets[i]), get<1>(offsets[i])), cv::Range::all());
    cout << m2.rows << " " << m2.cols << endl;
    
    // start threads
    threadsVec.push_back( thread(myFunction, ref(m2)));
  } 

I want to apply myFunction to subparts of the matrix in parallel. I checked the offsets and they are correct. I found out that if i print m2's dimensions (rows and columns) within the for it gives me the right dimensions for the matrix, while if I print it in myFunction method it gaves me 0 rows and 0 cols, what did I do wrong? How can I reach the right result?

Also, if I pass directly the entire m1 matrix it works correctly.

CodePudding user response:

m2 is destroyed at the end of your loop. Keeping a reference on it is undefined behavior.

Just pass m2 by value instead. cv::Mat already behaves like a shared_ptr: copying a cv::Mat (and sub-matrices count as copies) won't deep-copy its internal buffer. So there's no need to use a reference on top of that.


Just in case, a reminder that cv::Mat::forEach() exists and allows you to apply an operation to each pixel in your matrix in parallel without having to bother about parallelization details. However it's limited to per-pixel operations only... so if you need to work on sub-image regions it won't do it.

  • Related