The common answer is to calculate the total number of elements in the matrix and multiply it by the size of each element, like this:
// Given cv::Mat named mat.
size_t sizeInBytes = mat.total() * mat.elemSize();
This will work in conventional scenarios, where the matrix was allocated as a contiguous chunk in memory.
But consider the case where the system has an alignment constraint on the number of bytes per row in the matrix. In that case, if mat.cols * mat.elemSize()
is not properly aligned, mat.isContinuous()
is false
, and the previous size calculation is wrong, since mat.elemSize()
will have the same number of elements, although the buffer is larger!
The correct answer, then, is to find the size of each matrix row in bytes, and multiply it with the number of rows:
size_t sizeInBytes = mat.step[0] * mat.rows;
Read more about step
here.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…