A faster way to get color components from an image is to represent the image as an IplImage structure, and then use the pixel size and the number of channels to iterate through it using pointer arithmetic.
For example, if you know that your image is a three-channel image with 1 byte per pixel, and its format is BGR (by default in OpenCV), the following code will access its components:
(In the following code, img is of type IplImage .)
for (int y = 0; y < img->height; y++) { for(int x = 0; x < img->width; x++) { uchar *blue = ((uchar*)(img->imageData + img->widthStep*y))[x*3]; uchar *green = ((uchar*)(img->imageData + img->widthStep*y))[x*3+1]; uchar *red = ((uchar*)(img->imageData + img->widthStep*y))[x*3+2]; } }
For a more flexible approach, you can use the CV_IMAGE_ELEM macro defined in types_c.h :
#define CV_IMAGE_ELEM( image, elemtype, row, col ) \ (((elemtype*)((image)->imageData + (image)->widthStep*(row)))[(col)])
Daniel MartΓn
source share