将图片存储到GPU

瘦欲@ 提交于 2019-12-28 12:24:10

将图片存储到GPU分为两步:在GPU上分配内存,将图片从CPU复制到GPU。

  1. 在GPU上分配内存
cudaMallocPitch( void** devPtr,size_t* pitch,size_t widthInBytes,size_t height )

示例代码:

void CudaImage::Allocate(int w, int h, int p, bool host, float *devmem, float *hostmem) 
{
  width = w;
  height = h; 
  pitch = p; 
  d_data = devmem;
  h_data = hostmem; 
  t_data = NULL; 
  if (devmem==NULL) {
    safeCall(cudaMallocPitch((void **)&d_data, (size_t*)&pitch, (size_t)(sizeof(float)*width), (size_t)height));
    pitch /= sizeof(float);
    if (d_data==NULL) 
      printf("Failed to allocate device data\n");
    d_internalAlloc = true;
  }
  if (host && hostmem==NULL) {
    h_data = (float *)malloc(sizeof(float)*pitch*height);
    h_internalAlloc = true;
  }
}

2.将图片由CPU复制到GPU

 cudaMemcpy2D ( void* dst, size_t dpitch, const void* src, size_t spitch, size_t width, size_t height, cudaMemcpyHostToDevice )

示例代码:

double CudaImage::Download()  
{
  TimerGPU timer(0);
  int p = sizeof(float)*pitch;
  if (d_data!=NULL && h_data!=NULL) 
    safeCall(cudaMemcpy2D(d_data, p, h_data, sizeof(float)*width, sizeof(float)*width, height, cudaMemcpyHostToDevice));
  double gpuTime = timer.read();
#ifdef VERBOSE
  printf("Download time =               %.2f ms\n", gpuTime);
#endif
  return gpuTime;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!