c++ - 将并行 CUDA 程序转换为顺序运行

标签 c++ cuda image-manipulation sequential

我有以下 CUDA 程序,可以将图像从 RGBA 并行转换为灰度。我还想有一个按顺序运行的版本,这样我就可以比较两者并获得诸如加速等指标。

根据我的理解,为了使其按顺序运行,我需要以一种方式进行编辑,这意味着图像使用两个 for 循环(一个用于 X,一个用于 Y)逐个像素地逐步执行。然后应在像素上运行灰度转换,然后再移动到下一个像素。

虽然我对我应该做什么有所了解,但我不确定我应该在哪里编辑代码以及从哪里开始。

编辑:我现在明白我需要编辑的是内核本身,以使我的程序顺序运行。

如下所示,

 __global__ void colorConvert(unsigned char * grayImage, unsigned char * rgbImage, unsigned int width, unsigned int height)
{
    unsigned int x = threadIdx.x + blockIdx.x * blockDim.x;
    //unsigned int y = threadIdx.y + blockIdx.y * blockDim.y; //this is needed if you use 2D grid and blocks
    //if ((x < width) && (y < height)) {
    //check if out of bounds
    if ((x < width*height)) {
        // get 1D coordinate for the grayscale image
        unsigned int grayOffset = x;// y*width + x; //this is needed if you use 2D grid and blocks
        // one can think of the RGB image having
        // CHANNEL times columns than the gray scale image
        unsigned int rgbOffset = grayOffset*CHANNELS;
        unsigned char r = rgbImage[rgbOffset]; // red value for pixel
        unsigned char g = rgbImage[rgbOffset + 1]; // green value for pixel
        unsigned char b = rgbImage[rgbOffset + 2]; // blue value for pixel
        // perform the rescaling and store it
        // We multiply by floating point constants
        grayImage[grayOffset] = 0.21f*r + 0.71f*g + 0.07f*b;
    }
}

我已经从问题中删除了我的其余代码,因为其中有很多代码也被浏览过。如果我想让这个内核以顺序方式运行,使用两个 for 循环遍历每个像素并将 grayImage[grayOffset] 代码行应用于每个像素,我将如何去做?

最佳答案

您需要一个 for 循环,在您的代码中,您对所有图像像素使用一维数组,因此您只需要一个 for。

我认为循环可以这样写,在一个函数中,该函数采用与内核相同的参数

for(x=0; x<width*height; ++x)
{
    unsigned int grayOffset = x;
    unsigned int rgbOffset = grayOffset*CHANNELS;
    unsigned char r = rgbImage[rgbOffset]; // red value for pixel
    unsigned char g = rgbImage[rgbOffset + 1]; // green value for pixel
    unsigned char b = rgbImage[rgbOffset + 2]; // blue value for pixel
    // perform the rescaling and store it
    // We multiply by floating point constants
    grayImage[grayOffset] = 0.21f*r + 0.71f*g + 0.07f*b;

}

关于c++ - 将并行 CUDA 程序转换为顺序运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42651600/

相关文章:

cuda - 具有暂存缓冲区的 NPP 函数不会填充输出值

image-manipulation - 生成图像旋转版本的工具

C++ 无法实例化抽象类子类

c++ - 3d 实时软件渲染器开源

tensorflow - 哪些 TensorFlow 和 CUDA 版本组合兼容?

javascript - 当我将缩略图附加到 DIV 时,如何以特定模式定位缩略图?

c# - 为什么 GDI+ 会截断缩放后的图像?

C++:在派生类的对象上调用函数的函数调用优先级规则?

c++ - CMake 项目中的 qmake 子项目

c++ - cudaDeviceReset 诉 cudaFree