【问题标题】:Calling userdefined functions in thrust在推力中调用用户定义的函数
【发布时间】:2013-05-28 13:43:34
【问题描述】:

我正在使用 OpenCV 加载一个.png 文件,我想使用推力库提取它的蓝色强度值。

我的代码是这样的:

  1. 使用 OpenCV IplImage 指针加载图像
  2. 将图像数据复制到thrust::device_vector
  3. 使用推力库从结构内的设备矢量中提取蓝色强度值。

现在我在从设备向量中提取蓝色强度值时遇到问题。

  • 我在 cuda 中编写了这段代码,现在已经使用推力库对其进行了转换。
  • 我在此函数中获取蓝色强度值。
  • 我想知道如何从主函数调用这个结构FetchBlueValues

代码:

#define ImageWidth 14
#define ImageHeight 10

thrust::device_vector<int> BinaryImage(ImageWidth*ImageHeight);
thrust::device_vector<int> ImageVector(ImageWidth*ImageHeight*3);

struct FetchBlueValues
{
    __host__ __device__ void operator() ()
    {
        int index = 0 ;
        for(int i=0; i<= ImageHeight*ImageWidth*3 ; i = i+3)
        {
            BinaryImage[index]= ImageVector[i];
            index++;
        }
    }
};

void main()
{
    src = cvLoadImage("../Input/test.png", CV_LOAD_IMAGE_COLOR);

    unsigned char *raw_ptr,*out_ptr;
    raw_ptr = (unsigned char*) src->imageData;

    thrust::device_ptr<unsigned char> dev_ptr = thrust::device_malloc<unsigned char>(ImageHeight*src->widthStep);

    thrust::copy(raw_ptr,raw_ptr+(src->widthStep*ImageHeight),dev_ptr);
    int index=0;
    for(int j=0;j<ImageHeight;j++)
    {
        for(int i=0;i<ImageWidth;i++)
        {
            ImageVector[index] = (int) dev_ptr[ (j*src->widthStep) + (i*src->nChannels) + 0 ];
            ImageVector[index+1] = (int) dev_ptr[ (j*src->widthStep) + (i*src->nChannels) + 1 ];
            ImageVector[index+2] = (int) dev_ptr[ (j*src->widthStep) + (i*src->nChannels) + 2 ];

            index +=3 ;
        }
    }

}

【问题讨论】:

  • 您的代码存在许多问题。您是否阅读过thrust quickstart(正如我之前向您建议的那样?)那里(以及许多其他地方)给出了在推力代码中使用用户定义的仿函数的示例(例如 saxpy 仿函数)。 Here is an example 我写的可能与您正在尝试做的事情一致。但是,您的仿函数可能不需要循环
  • 您也可以考虑避免使用仿函数和数据提取,而只使用strided range access mechanism
  • 谢谢你。我在我的代码中尝试了跨步范围访问机制,它可以工作......但它是否在设备内部运行?
  • 是的,如果您在device_vector 上运行,那么它正在设备内部运行。例如,在我链接的示例代码中,thrust::fill 操作正在设备上运行(使用strided_range 迭代器访问特定元素)。
  • 好的,谢谢...我的代码运行良好。

标签: c opencv cuda thrust


【解决方案1】:

由于图像以像素格式存储,并且每个像素都包含不同的颜色,因此在访问每个像素的各个颜色分量时存在自然的“跨度”。在这种情况下,像素的颜色分量似乎存储在每个像素三个连续的int 数量中,因此给定颜色分量的访问步幅将是三个。

here 介绍了一个跨步范围访问迭代器方法示例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-22
    • 1970-01-01
    • 2011-01-31
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 2011-05-19
    • 1970-01-01
    相关资源
    最近更新 更多