将 cv::Mat 向量复制到浮点数向量的最佳方法是什么?

What is the best way to copy a vector of cv::Mat to a vector of float?

本文关键字:向量 方法 最佳 是什么 cv Mat 复制 浮点数      更新时间:2023-10-16

>假设我们有一组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() - 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);
}