In "Learning OpenCV" by Gary Bradski & Adrian Kaehler there is a section on the CvMat matrix structure that contains the following example code (it is Example 3-9: Summing all the elements in a single-channel matrix)
float sum( const CvMat* mat ) {
float s = 0.0f;
for(int row=0; row<mat->rows; row++ ) {
const float* ptr = (const float *)(mat->data.ptr + row * mat->step);
for(int col=0; col<mat->cols; col++ ) {
s += *ptr++;
}
}
return( s );
}
There are a couple of things I do not understand about this code, but they may be the result of me not using C for many many years rather than OpenCV questions.
Why
const
? Sinceptr
is incremented later in the function I do not understand why it is declaredconst
.Why
.ptr
? The authors point out that "When computing the pointer into the matrix, remember that the matrix elementdata
is a union. Therefore, when de-referencing this pointer, you must indicate the correct element of the union in order to obtain the correct pointer type." So why not use the union memberfl
with typefloat*
so that the line of code would befloat* ptr = mat->data.fl + row * mat->step;
instead of taking ptr
with type uchar*
and requiring an additional cast?