CUDA:如何存储持久数据?

时间:2012-04-21 11:35:56

标签: cuda

我想在CUDA中将背景图像数据存储在设备上。后来当我从视频源读取新场景时,我想将新场景作为前景图像发送到GPU并从背景图像中减去它。我不希望为每个场景重新发送背景图像到GPU。我怎么能这样做?

2 个答案:

答案 0 :(得分:3)

将背景图像存储在设备存储器阵列中(即在GPU上)。然后,当您读取前景图像时,使用cudaMemcpy将其复制到另一个设备内存阵列。然后启动一个内核,它将两个设备内存数组作为参数并执行图像减法。应该很简单。

假设您使用默认上下文创建并且这一切都在同一个CPU线程中运行,您不必担心做任何特定的事情来保持您的CUDA上下文“完整​​”,如Bart所评论的那样。但是,如果您执行任何CPU多线程,则需要进行一些上下文管理。

答案 1 :(得分:1)

这是一个简单的例子..

int main(int argc, char **argv) {
    uint *hostBackground, *hostForeground; //new uint[]..
    uint *background, *foreground;

首先初始化你的背景和前景数据..

    cudaMalloc(background, ..);
    cudaMalloc(foreground, ..);

然后加载背景数据

    cudaMemCpy(background, hostBackground, ..); //copy to device..

然后读取前景数据

    while (applicationRuns) {
        readImage(hostForeground); //read image..
        cudaMemcpy(foreground, hostForeground, ..); //copy to device

        //operate on foreground..
        substruct_kernel<<<threads, blocks>>>(foreground, background, width, height);

        cudaMemcpy(hostForeground, foreground, ..); //copy to host

        //use hostForeground
    }

释放他们

    cudaFree(foreground);
    cudaFree(background);
}

这是一个简单的子结构内核..

__global__ void substruct_kernel(uint *foreground, uint *backgroung, int width, int height)
{
    int idx = threadIdx.x + threadDim.x * blockIdx.x;
    int idy = threadIdx.y + threadDim.y * blockIdx.y;

    if (idx < width && idy < height)
       foreground[idx + idy * width] -= background[idx + idy * width]; //clamp may be required..
}

我建议使用库进行这样简单的操作。 Blas库或Thrust库可能是选项。