OpenCV 4 Computer Vision Application Programming Cookbook(Fourth Edition)
上QQ阅读APP看书,第一时间看更新

Low-level pointer arithmetics

In the cv::Mat class, the image data is contained in a memory block of unsigned characters. The address of the first element of this memory block is given by the data attribute that returns an unsigned character pointer. So, to start your loop at the beginning of the image, you could have written the following code:

uchar *data= image.data; 

Moving from one row to the next could have been done by moving your row pointer using the effective width as follows:

data+= image.step;  // next line

The step method gives you the total number of bytes (including the padded pixels) in a line. In general, you can obtain the address of the pixel at row j and column i as follows:

// address of pixel at (j,i) that is &image.at(j,i)      
data= image.data+j*image.step+i*image.elemSize();     

However, even if this would work in our example, it is not recommended that you proceed in that way.