c++ - 将 cv::Mat vector 复制到 float vector 的最佳方法是什么?

标签 c++ opencv vector

假设我们有一组 cv::Mat所有相同类型的对象 CV_32F和相同的大小:这些矩阵之前已插入到 vector<cv::Mat> 中.

// input data
vector<cv::Mat> src;

我想复制 src 中的所有元素 vector 成一个单一的vector<float>目的。换句话说,我想复制(到目标 vector )所有 float src 的矩阵中包含的元素 vector 。

// 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() -- datastartdataend 必须保持不变。试试这个:

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++ - 将 cv::Mat vector 复制到 float vector 的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28035600/

相关文章:

ios - 如何以编程方式将矢量图像放入 iOS Assets 目录

c++ - 字符数组的 vector

c++ - SDL2 CreateRenderer 抛出无效窗口错误

c++ - 为什么允许在初始化列表中从 const 指针到 const 转换为 const 指针到非常量

c++ - #include <cmath> : "In FIle included from" error message?

c++ - imwrite opencv 会影响捕获时间吗?

c++ - 保留 vector 值的拷贝,然后将其覆盖

c++ - 为什么 Mat.forEach 不会改变自己?

python - 减少不透明度的图像对齐

c++ - vector 加上 unique_ptr 到一个对象,内存没有释放?