查找cv :: Mat的字节大小 [英] Finding the size in bytes of cv::Mat

查看:1251
本文介绍了查找cv :: Mat的字节大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将OpenCV与cv::Mat对象一起使用,并且我需要知道矩阵占用的字节数才能将其传递给低级C API.似乎OpenCV的API没有返回矩阵使用的字节数的方法,而且我只有一个原始的uchar *data公共成员,而没有包含其实际大小的成员.

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.

如何找到以字节为单位的cv::Mat大小?

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

推荐答案

常见的答案是计算矩阵中元素的总数,然后将其乘以每个元素的大小,如下所示:

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.

但是请考虑系统对矩阵中每行的字节数具有对齐约束的情况.在这种情况下,如果mat.cols * mat.elemSize()没有正确对齐,则mat.isContinuous()false,并且以前的大小计算是错误的,因为mat.elemSize()将具有相同数量的元素,尽管缓冲区更大!

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;

此处了解更多信息.

这篇关于查找cv :: Mat的字节大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆