Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

opencv - Finding the size in bytes of cv::Mat

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...