Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

const float union ptr in Bradski & Kaehler's “Learning OpenCV” Example 3-9

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.

  1. Why const? Since ptr is incremented later in the function I do not understand why it is declared const.

  2. Why .ptr? The authors point out that "When computing the pointer into the matrix, remember that the matrix element data 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 member fl with type float* so that the line of code would be

    float* ptr = mat->data.fl + row * mat->step;
    

instead of taking ptr with type uchar* and requiring an additional cast?

const float union ptr in Bradski & Kaehler's “Learning OpenCV” Example 3-9

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.

  1. Why const? Since ptr is incremented later in the function I do not understand why it is declared const.

  2. Why .ptr? The authors point out that "When computing the pointer into the matrix, remember that the matrix element data 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 member fl with type float* so that the line of code would be

    float* ptr = mat->data.fl + row * mat->step;
    

instead of taking ptr with type uchar* and requiring an additional cast?