使用 TBB 并行化 OpenCV 代码

发布于 2024-10-30 16:01:30 字数 621 浏览 6 评论 0原文

我正在尝试使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

三五鸿雁 2024-11-06 16:01:30

setImageROI() 不是只读操作。显然,因为它正在改变图像的状态。即使它不会崩溃,您的某些复制操作也会在错误的 ROI 上运行(由不同的线程设置)。

解决您的问题的方法是使用 OpenCV C++ API!

您有一个 cv::Mat 而不是 IplImage。然后,您可以使用如下代码:

// given: cv::Mat image
// returns: cv::Mat dest
cv::Rect roi(curWidth - 2, 0, 5, 5);
cv::Mat local(image, roi);
cv::Mat dest(...);
local.copyTo(dest);

现在为什么这是线程安全的?显然,原始图像的状态没有改变。相反,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:

// given: cv::Mat image
// returns: cv::Mat dest
cv::Rect roi(curWidth - 2, 0, 5, 5);
cv::Mat local(image, roi);
cv::Mat dest(...);
local.copyTo(dest);

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文