I am trying to parallelize some Image Matching code written in OpenCV using TBB. Problem is that according to me matching (creating a 5×5 window in left image and looking for match in right pixel by pixel) is essentially a read only operation and currently I am trying to parallelize the inner loop ( ie at a given height. I assign different pixels to different threads). To my surprise though the cvSetImageROI command breaks when done in parallel. Here is the code.
//Code below just carves out a window(5x5) at a current width which is to be matched
cvSetImageROI(leftImageROI, cvRect(curWidth - 2, 0, 5, 5));
IplImage* currentROI = cvCreateImage(cvSize(5, 5), leftImageROI->depth, leftImageROI->nChannels);
cvCopy(leftImageROI, currentROI);
cvResetImageROI(leftImageROI);
Now all this looks thread safe to me since they are only reading images.However code crashes. If I put a lock at the very beginning though it works. Can someone help ?
setImageROI() is not a read-only operation. Obviously, as it is changing the state of the image. Even if it would not crash, some of your copy operations would operate on the wrong ROI (as set by a different thread).
The solution to your problem is to use the OpenCV C++ API!
There you have a cv::Mat instead of IplImage. Then, you can use code like this:
Now why is this thread-safe? Obviously, the state of the original image is not changed. Instead, the ROI is written to a new, thread-local matrix header.