将 cv::Mat 向量复制到浮点数向量的最佳方法是什么?
What is the best way to copy a vector of cv::Mat to a vector of float?
>假设我们有一组cv::Mat
对象,所有对象类型相同,CV_32F
大小相同:这些矩阵之前已入到vector<cv::Mat>
中。
// input data
vector<cv::Mat> src;
我想将所有元素从src
向量复制到单个vector<float>
对象中。换句话说,我想复制(到目标向量)src
向量矩阵中包含的所有float
元素。
// destination vector
vector<float> dst;
我目前正在使用以下源代码。
vector<cv::Mat>::const_iterator it;
for (it = src.begin(); it != src.end(); ++it)
{
vector<float> temp;
it->reshape(0,1).copyTo(temp);
dst.insert(dst.end(), temp.begin(), temp.end());
}
为了提高复制的速度,我测试了下面的代码,但我只得到了 5% 的加速。为什么?
vector<cv::Mat>::const_iterator it;
for (it = src.begin(); it != src.end(); ++it)
{
Mat temp = it->reshape(0,1); // reshape the current matrix without copying the data
dst.insert(dst.end(), (float*)temp.datastart, (float*)temp.dataend);
}
如何进一步提高复制速度?
应使用 vector::reserve()
以避免在插入时重复重新分配和复制。 如果不复制数据,则不需要使用reshape()
- datastart
和dataend
必然保持不变。 试试这个:
dst.reserve(src.size() * src.at(0).total()); // throws if src.empty()
for (vector<cv::Mat>::const_iterator it = src.begin(); it != src.end(); ++it)
{
dst.insert(dst.end(), (float*)src.datastart, (float*)src.dataend);
}
相关文章:
- C++从另一个类访问公共静态向量的正确方法是什么
- 有没有一种"cleaner"的方法可以在指向基的指针向量中找到派生类的第一个实例?
- 声明高维向量的更简洁的方法
- 在C++中初始化向量映射的最有效方法
- C++11 迭代向量的新方法?
- std::find,返回所有找到的值的替代方法,而不仅仅是存在重复的向量的第一个值
- C++ STD 函数运算符:有没有一种方法可以通过函数将一个向量映射到另一个向量上?
- C++:将向量传递到构造函数以创建成员变量的最佳方法?
- 有什么方法可以将具有不同模板参数的模板类实例放入向量中?
- 当映射包含字符串向量作为值时,从值中获取键的有效方法
- 在向量中查找大于 0(或通常为 k)的最小元素的最佳方法是什么?
- 从数组中删除非唯一值、保持顺序和不使用向量的最佳方法?
- 使用192/256位整数求和无符号64位整数向量的点积的最快方法
- 访问类成员向量最后一项的正确方法
- 使用 std::vector::swap 方法在C++中交换两个不同的向量是否安全?
- 从列表/向量制作嵌套 for 循环的最佳方法是什么?
- 检查两个向量是否并行的最有效方法
- 如何从 node-ffi 调用 c++ 中以结构向量作为参数的方法?
- 返回向量元素的 l 值的正确方法是什么?
- 如何在方法主体中返回声明向量的引用?