使用CUDA优化嵌套的for循环

时间:2012-09-23 00:28:52

标签: cuda gpu

所以我有一个我正在研究的项目,它使用OpenCV来检测移动物体中的运动。我正在尝试加速检测,并有一个嵌套的for循环,我想加速使用CUDA。我在Visual Basic中设置了所有CUDA集成。这是我的.cpp文件中的嵌套for循环。

      for (int i=0; i<NumberOfFeatures; i++)
  {
    // Compute integral image.
    cvIntegral(mFeatureImgs[i], mFirstOrderIIs[i]);

    for (int j=0; j<NumberOfFeatures; j++)
    {
      // Compute product feature image.
      cvMul(mFeatureImgs[i], mFeatureImgs[j], mWorker);

      // Compute integral image.
      cvIntegral(mWorker, mSecondOrderIIs[i][j]);
    }
  }

我对CUDA比较陌生,所以我的问题是,有人能告诉我一个如何使用CUDA让这个嵌套for循环变得更快的例子吗?

2 个答案:

答案 0 :(得分:2)

正如sgar91所指出的,OpenCV包含一个GPU模块,如下所述:

http://opencv.willowgarage.com/wiki/OpenCV_GPU

该wiki还建议如何在雅虎的OpenCV帮助论坛上提出GPU相关问题。

有一个gpu加速图像积分函数。如果你环顾四周,你也可以找到cvMul的等价物。

您无法在非GPU代码和GPU版本中使用完全相同的数据类型。看看我之前发布的wiki页面上给出的“简短示例”示例。您将看到需要执行类似的操作将现有数据传输到可由GPU操作的数据结构:

    cv::gpu::GpuMat dst, src;  // this is defining variables that can be accessed by the GPU
    src.upload(src_host);      // this is loading the src (GPU variable) with the image data

    cv::gpu::threshold(src, dst, 128.0, 255.0, CV_THRESH_BINARY);  //this is causing the GPU to act

你需要做类似的事情,例如:

    cv::gpu::GpuMat dst, src;
    src.upload(src_data);

    cv::gpu::integral(src, dst);

答案 1 :(得分:1)

cv_integral基本上总结了两个维度的像素值 - 这只能通过矩阵运算来完成。所以,如果你愿意,你也可以试试arrayfire。 我创建了一个小例子如何使用矩阵进行图像处理:

// computes integral image
af::array cv_integral(af::array img) {

  // create an integral image of size + 1
  int w = img.dims(0), h = img.dims(1);
  af::array integral = af::zeros(w + 1, h + 1, af::f32);

  integral(af::seq(1,w), af::seq(1,h)) = img;

  // compute inclusive prefix sums along both dimensions
   integral = af::accum(integral, 0);
   integral = af::accum(integral, 1);

   std::cout << integral << "\n";

   return integral;
}

void af_test()
{
 int w = 6, h = 5; // image size
 float img_host[] = {5,2,3,4,1,7,
                    1,5,4,2,3,4,
                    2,2,1,3,4,45,
                    3,5,6,4,5,2,
                    4,1,3,2,6,9};

  //! create a GPU image (matrix) from the host data
  //! NOTE: column-major order!!
  af::array img(w, h, img_host, af::afHost);

   //! create an image from random data
   af::array img2 = af::randu(w, h) * 10;
   // compute integral images
   af::array integral = cv_integral(img);
   // elementwise product of the images
   af::array res = integral * img2;
   //! compute integral image
   res = cv_integral(res);
   af::eval(res);
   std::cout << res << "\n";
}
相关问题