andrestoga
andrestoga

Reputation: 619

Understanding address computing in Opencv's CV Mat structure

I don't understand the address of a 2-dimensional array Mat struture for a given point is computed as:

addr(M_{i,j}) = M.data + M.step[0]*i + M.step[1]*j

And why???

M.step[i] >= M.step[i+1] (in fact, M.step[i] >= M.step[i+1]*M.size[i+1] )

For example, if we have a 2-dimensional array with size 5X10. The way I know how to compute the address for the point (4,7) is the following:

Address = 4 + 7*5

Could someone shed some light on it??

Best regards,

Upvotes: 1

Views: 493

Answers (1)

Michael Burdinov
Michael Burdinov

Reputation: 4438

1) Address you are talking about is index in the array, not address in computer memory. For example, if you have an array that occupies memory between 10000 to 20000, than address of pixel at point (0,0) is 10000, not 0.

2) Image may have more than one channels and pixel values may use more than one byte. For example if you have matrix with 3 channels and pixels are ints (i.e. 4 bytes), than step[1] is 3x4=12 bytes. Address of pixel at (0,5) in such array will be 10000 + step[0] x 0 + 12 x 5.

3) Also your computation is missing the fact that matrix may not be continuous in memory, i.e. between end of one row and beginning of next one may be some gap. This is also incorporated in step[0].

Just a recommendation: don't bother too much with all those computations of steps. If you need to access random pixels in image use function 'at()', and if you work on the rows sequentially use 'ptr()' to get pointer to the beginning of the row. This will save you a lot of computations and potential bugs.

Upvotes: 2

Related Questions