OpenCV Examples Part 1

Nov 4, 2008 | Tags: OpenCV | del.icio.us del.icio.us | digg Digg

6. Access Image Data

Listing 5 below shows you a simple way to access image data using pointers. It loads an image, setup the pointer, and perform some manipulation to the image.

Listing 5: Access image data

  1. /* load the image */
  2. IplImage *img = cvLoadImage( argv[1], CV_LOAD_IMAGE_COLOR );
  3.  
  4. /* retrieve properties */
  5. int width     = img->width;
  6. int height    = img->height;
  7. int nchannels = img->nChannels;
  8. int step      = img->widthStep;
  9.  
  10. /* setup the pointer to access image data */
  11. uchar *data = ( uchar* )img->imageData;    
  12.  
  13. /* convert to grayscale manually */
  14. int i, j, r, g, b, byte;
  15. for( i = 0 ; i < height ; i++ ) {
  16.     for( j = 0 ; j < width ; j++ ) {
  17.         r = data[i*step + j*nchannels + 0];
  18.         g = data[i*step + j*nchannels + 1];
  19.         b = data[i*step + j*nchannels + 2];
  20.        
  21.         byte = ( r + g + b ) / 3;
  22.        
  23.         data[i*step + j*nchannels + 0] = byte;
  24.         data[i*step + j*nchannels + 1] = byte;
  25.         data[i*step + j*nchannels + 2] = byte;
  26.     }
  27. }

The code above converts the image to grayscale manually only for an example. It is more efficient and much simpler if we just use built-in OpenCV functions to perform image manipulations (using cvCvtColor in this case).