OpenCL leading with OpenCV

I’m trying to implement an image processing algorithm using OpenCL, so I think it could be a good idea to work with OpenCV.

I have the following:

    cv::Mat image = cv::imread("lena.bmp");
    width = image.rows;
    height = image.cols;
    
    char *buffer = reinterpret_cast<char *>(image.data);
    
    cl::Image2D clImage(context,
                            CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
                            cl::ImageFormat(CL_RGBA, CL_UNORM_INT8),
                            width,
                            height,
                            0,
                            buffer);

    return clImage;

But when I run the program it gives me a segfault:

    Segmentation fault (core dumped)

I was reading the OpenCL Programming Guide source code, and it implements a very similar code which I tested, and it works fine, but it uses freeimage:

    char *buffer = new char[width * height * 4];
    memcpy(buffer, FreeImage_GetBits(image), width * height * 4);

    FreeImage_Unload(image);

    // Create OpenCL image
    cl_image_format clImageFormat;
    clImageFormat.image_channel_order = CL_RGBA;
    clImageFormat.image_channel_data_type = CL_UNORM_INT8;

    cl_int errNum;
    cl_mem clImage;
    clImage = clCreateImage2D(context,
                            CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
                            &clImageFormat,
                            width,
                            height,
                            0,
                            buffer,
                            &errNum);

So, what’s the problem? How can I solve it?

The read image probably has a wrong format, such as BGR instead of RGBA. As a result, OpenCL attempts to read memory outside the image buffer.

I realized that I could do the following:

cv::Mat image = cv::imread("lena.bmp", CV_LOAD_IMAGE_COLOR);
    cv::Mat imageRGBA;
    
    width = image.rows;
    height = image.cols;
    
    cv::cvtColor(image, imageRGBA, CV_BGR2RGBA);
    char *buffer = reinterpret_cast<char *>(imageRGBA.data);
    
    cl::Image2D clImage(context,
                            CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
                            cl::ImageFormat(CL_RGBA, CL_UNORM_INT8),
                            width,
                            height,
                            0,
                            buffer);

    return clImage;

There exist any other way?