使用 TBB 并行化 OpenCV 代码
我正在尝试使用 TBB 并行化用 OpenCV 编写的一些图像匹配代码。问题是,根据我的匹配(在左图像中创建一个 5x5 窗口并在右像素中逐像素查找匹配)本质上是一个只读操作,目前我正在尝试并行化内部循环(即在给定的高度。我分配不同的像素对应不同的线程)。令我惊讶的是,cvSetImageROI
命令在并行执行时会中断。这是代码。
//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);
现在,所有这些对我来说看起来都是线程安全的,因为它们只读取图像。但是代码崩溃了。如果我在一开始就加锁的话,它会起作用。有人可以帮忙吗?
I am trying to parallelize some Image Matching code written in OpenCV using TBB. Problem is that according to me matching (creating a 5x5 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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
setImageROI() 不是只读操作。显然,因为它正在改变图像的状态。即使它不会崩溃,您的某些复制操作也会在错误的 ROI 上运行(由不同的线程设置)。
解决您的问题的方法是使用 OpenCV C++ API!
您有一个 cv::Mat 而不是 IplImage。然后,您可以使用如下代码:
现在为什么这是线程安全的?显然,原始图像的状态没有改变。相反,ROI 被写入新的线程本地矩阵头。
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.