There is an easy way to do this.
Mat has Mat.data gives a pointer which refers to the original data matrix.
To get pixel values of nth row and mth column,
Mat img = imread("filename.jpg",CV_LOAD_IMAGE_COLOR);
unsigned char *input = (unsigned char*)(img.data);
int i,j,r,g,b;
for(int i = 0;i < img.cols;i++){
for(int j = 0;j < img.rows;j++){
b = input[img.cols * j + i ] ;
g = input[img.cols * j + i + 1];
r = input[img.cols * j + i + 2];
}
}
So, this is about a colored image. for grayscale images,
Mat img = imread("filename.jpg",CV_LOAD_IMAGE_COLOR);
Mat g;
cvtColor(img, g, CV_BGR2GRAY);
unsigned char *input = (unsigned char*)(g.data);
int i,j,r,g,b;
for(int i = 0;i < img.cols;i++){
for(int j = 0;j < img.rows;j++){
g = input[img.cols * j + i];
}
}
Read more on this blogpost.