Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the size in bytes of cv::Mat

Tags:

opencv

I'm using OpenCV with cv::Mat objects, and I need to know the number of bytes that my matrix occupies in order to pass it to a low-level C API. It seems that OpenCV's API doesn't have a method that returns the number of bytes a matrix uses, and I only have a raw uchar *data public member with no member that contains its actual size.

How can one find a cv::Mat size in bytes?

like image 280
StatusReport Avatar asked Oct 18 '14 14:10

StatusReport


1 Answers

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.

like image 82
StatusReport Avatar answered Oct 16 '22 11:10

StatusReport