将cv :: Mat的行转换为std :: vector [英] Converting a row of cv::Mat to std::vector
问题描述
我有一个相当简单的问题:如何取一行 cv :: Mat
并获取 std :: vector
? cv :: Mat
包含 doubles
(为了问题的目的,它可以是任何简单的数据类型) p>
通过OpenCV文档只是很混乱,除非我的书签页面我找不到一个文档页面两次Googling,只有很多,不容易导航。
我发现 cv :: Mat :: at(..)
可以访问Matrix元素,我记得从 C OpenCV
,有至少3种不同的方式来访问元素,所有他们用于不同的目的...不记得什么用于: /
因此,复制Matrix元素一个元素一定会起作用,我正在寻找一种效率更高的方法,
OpenCV中的数据矩阵以行为主的顺序布置,使得每行被保证是连续的。这意味着您可以将行中的数据解释为纯C数组。以下示例直接来自文档:
//计算正矩阵元素的总和
//(假设M是双精度矩阵)
double sum = 0;
for(int i = 0; i {
const double * Mi = M.ptr double(i);
for(int j = 0; j sum + = std :: max(Mi [j],0。
}
因此,最有效的方法是将普通指针传递给 std :: vector
:
//指向第i行的指针
const double * p = mat.ptr double(i);
//将数据复制到向量。注意(p + mat.cols)指向行的
//结尾。
std :: vector< double> vec(p,p + mat.cols);
这肯定比使用 begin code>和
end()
,因为那些涉及额外的计算以支持行之间的间隙。
I have a fairly simple question: how to take one row of cv::Mat
and get all the data in std::vector
? The cv::Mat
contains doubles
(it can be any simple datatype for the purpose of the question).
Going through OpenCV documentation is just very confusing, unless I bookmark the page I can not find a documentation page twice by Googling, there's just to much of it and not easy to navigate.
I have found the cv::Mat::at(..)
to access the Matrix element, but I remember from C OpenCV
that there were at least 3 different ways to access elements, all of them used for different purposes... Can't remember what was used for which :/
So, while copying the Matrix element-by-element will surely work, I am looking for a way that is more efficient and, if possible, a bit more elegant than a for loop for each row.
Data in OpenCV matrices is laid out in row-major order, so that each row is guaranteed to be contiguous. That means that you can interpret the data in a row as a plain C array. The following example comes directly from the documentation:
// compute sum of positive matrix elements
// (assuming that M is double-precision matrix)
double sum=0;
for(int i = 0; i < M.rows; i++)
{
const double* Mi = M.ptr<double>(i);
for(int j = 0; j < M.cols; j++)
sum += std::max(Mi[j], 0.);
}
Therefore the most efficient way is to pass the plain pointer to std::vector
:
// Pointer to the i-th row
const double* p = mat.ptr<double>(i);
// Copy data to a vector. Note that (p + mat.cols) points to the
// end of the row.
std::vector<double> vec(p, p + mat.cols);
This is certainly faster than using the iterators returned by begin()
and end()
, since those involve extra computation to support gaps between rows.
这篇关于将cv :: Mat的行转换为std :: vector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!