2

Is this the correct way of accessing all pixels in cv::Mat:

for( row = 0; row < mat.rows; ++row) 
    {
            for ( col = 0; col < mat.cols; ++col) 
            {



            }
    }

Or is there a formula method similar to this formula for an IplImage *:

temp_ptr = &((uchar*)(img->imageData + (img->widthStep*pt.x)))[pt.y*3];
Expert Novice
  • 1,867
  • 4
  • 21
  • 47
  • 1
    Do you know `Mat` has one public field called `data` of type `uchar`? – Nawaz Oct 22 '11 at 16:37
  • @Nawaz - Yes sir i know about that, please help me out, i am struggling a bit out here, i know that is the pointer to the data, but how do i cycle through pixels, i can get work with the rgb values with data but not cycle through it. – Expert Novice Oct 22 '11 at 16:42

1 Answers1

1

In the best case, where all the pixels are stored contiguously you should be able to do:

uchar* pixel = mat.data;
for(int i = 0; i < mat.rows * mat.cols; ++i) 
{
    // access pixel[0],pixel[1],pixel[2] here
    pixel += 3; // move to next pixel
}

To be a bit more generic, but still fast, have a look at the sample code mentioned with Mat::isContinuous(). The general formula for calculating the address of an element can be seen here (Reproduced below).

Address calculation

user786653
  • 26,194
  • 3
  • 39
  • 50