cv::Mat::forEach() method race condition

asked 2017-09-20 08:25:21 -0600

hovnatan gravatar image

I have the following code, where I am trying to utilize the multithreaded access to elements of an OpenCV cv::Mat class using the forEach() member method. But when I run this code in valgrind --tool=helgrind I get multiple race condition reports. Also it doesn't work as intended, i.e., mask the image with another image. What is the reason for this behavior?

#include <opencv2/opencv.hpp>

int main(int argc, char** argv)
{
  cv::Mat1f im(21, 21, 0.0f);
  im(cv::Rect(7, 7, 7, 7)) = 0.5;
  cv::Mat1b mask(21, 21, 0.0);
  mask(cv::Rect(9, 9, 3, 3)) = 1;
  cv::Mat1f result(21, 21, 0.0f);
  mask.forEach([&result, &im] (uchar val, const int* pos)
  {
    if (val == 0)
      result(pos[1], pos[0]) = 0;
    else
      result(pos[1], pos[0]) = im(pos[1], pos[0]);
  });
  return 0;
}
edit retag flag offensive close merge delete

Comments

yea, why use a simple: im.copyTo(result, mask) , when you can have fun with lambdas, foreach & threads ;)

berak gravatar imageberak ( 2017-09-20 08:31:49 -0600 )edit

oh, btw, forEach() is already parallel (using parallel_for_)

berak gravatar imageberak ( 2017-09-20 08:38:30 -0600 )edit