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
/* load the image */
IplImage *img = cvLoadImage( argv[1], CV_LOAD_IMAGE_COLOR );
/* retrieve properties */
int width = img->width;
int height = img->height;
int nchannels = img->nChannels;
int step = img->widthStep;
/* setup the pointer to access image data */
uchar *data = ( uchar* )img->imageData;
/* convert to grayscale manually */
int i, j, r, g, b, byte;
for( i = 0 ; i < height ; i++ ) {
for( j = 0 ; j < width ; j++ ) {
r = data[i*step + j*nchannels + 0];
g = data[i*step + j*nchannels + 1];
b = data[i*step + j*nchannels + 2];
byte = ( r + g + b ) / 3;
data[i*step + j*nchannels + 0] = byte;
data[i*step + j*nchannels + 1] = byte;
data[i*step + j*nchannels + 2] = byte;
}
}
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).