OpenCV cv :: Mat & CvMat line alignment

can someone explain to me how OpenCV CvMat line alignment works (or its C ++ version of cv::Mat )? For example, let's say I have a matrix

 CvMat *cvmat = cvCreateMat(2,3,CV_8UC1); cvSet2D( cvmat, 0, 0, cvScalar(1) ); cvSet2D( cvmat, 0, 1, cvScalar(2) ); cvSet2D( cvmat, 0, 2, cvScalar(3) ); cvSet2D( cvmat, 1, 0, cvScalar(4) ); cvSet2D( cvmat, 1, 1, cvScalar(5) ); cvSet2D( cvmat, 1, 2, cvScalar(6) ); 

According to the CvMat documentation, the rows should be aligned by 4 bytes, that is, the first row of the matrix should be supplemented with one zero, and the second should begin with an offset of +4). However, if I debug this piece of code, the data is continuous (ie cvmat->data is [1,2,3,4,5,6] ), and I do not see 4-byte alignment. Is this a mistake in the documentation and is it always safe to consider the continuity of data as CvMat or cv::Mat (if the matrix is ​​not part of another from c)? Or are there some special configurations that might have some data gaps as a result of memory alignment?

+4
source share
1 answer

It is unsafe to assume continuity. cv::Mat has an isContinuous member isContinuous that you can check for continuity (the C API has a macro for this, as the comment says):

 // returns true iff the matrix data is continuous // (ie when there are no gaps between successive rows). // similar to CV_IS_MAT_CONT(cvmat->type) bool isContinuous() const; 

There is also a step member that tells you the offset between consecutive lines:

 // a distance between successive rows in bytes; includes the gap if any size_t step; 

So, if you have an 8-bit single-channel image, the pixel at the point (x, y) is at the offset y * step + x .

Here a number of situations arise when you get non-continuous memory, and they are not limited to aligning the memory. For example, if you say cv::Mat r = mat.col(0) , the data is not copied, but r points to the same memory area as mat , just with a different β€œheader”, so the β€œspace” that you have yes, is the data from a matrix that is not in column 0.

+3
source

All Articles