Search code examples
copencvcudathrust

Calling userdefined functions in thrust


I'm loading a .png file using OpenCV and I want to extract its blue intensity values using thrust library.

My code goes like this:

  1. Loading an image using OpenCV IplImage pointer
  2. Copying the image data into thrust::device_vector
  3. Extracting the blue intensity values from the device vector inside a structure using thrust library.

Now I have a problem in extracting Blue Intensity values from the device vector.

  • I did this code in cuda already now converting it using thrust library.
  • I fetch blue intensity values inside this function.
  • I want to know how to call this struct FetchBlueValues from the main function.

Code:

#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 ;
        }
    }

}

Solution

  • Since the image is stored in pixel format, and each pixel includes distinct colors, there is a natural "stride" in accessing the individual color components of each pixel. In this case, it appears that the color components of a pixel are stored in three successive int quantities per pixel, so the access stride for a given color component would be three.

    An example strided range access iterator methodology is covered here.