Read-back of an image from GPU memory and display using OpenCV


I have Tesla K20C card. I follow steps as below to display gray=scale image (resolution 512x512 pixels) from GPU memory:

  1. Read an image using OpenCV
  2. Write the image data to GPU memory
  3. Read back image data from GPU memory back to CPU memory
  4. Display the image in CPU by using OpenCV.

Problem Faced: The output image displayed at Step 4 is fully black.Can someone suggest the reason for this issue.


#include <cuda_runtime.h>
#include <opencv2/opencv.hpp>
#include “opencv2/highgui/highgui.hpp”

using namespace cv;
using namespace std;

int main(int argc, char** argv)
const int width = 640, height = 480;
IplImage* img = cvLoadImage(“PIC00001.tif”, CV_LOAD_IMAGE_GRAYSCALE);
IplImage* out_img;
const int bytes = img->widthStep * img->height;

unsigned char *dSrc;
cudaMalloc((void **)&dSrc,bytes * sizeof(unsigned char));
cudaMemcpy(dSrc,img->imageData,bytes* sizeof(unsigned char),cudaMemcpyHostToDevice);
cudaMemcpy(out_img->imageData,dSrc,bytes* sizeof(unsigned char),cudaMemcpyDeviceToHost);


return 0;


Maybe your CUDA installation is broken. Any time you are having trouble with cuda, you should use proper cuda error checking, and run your code with cuda-memcheck. If you’re not sure what proper cuda error checking is, google “proper cuda error checking” and take the first hit and start reading.

As a further diagnostic, I would also try doing a cvShowImage on the input image, to see if that is black also. If it is, that would pretty much rule out CUDA, and now you have just an OpenCV issue.