简体   繁体   中英

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

Suppose we have a set of cv::Mat objects, all of the same type CV_32F and the same size: these matrices have been previously inserted into a vector<cv::Mat> .

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

I want to copy all the elements from the src vector into a single vector<float> object. In other words, I want to copy (to a destination vector) all the float elements contained in the matrices of the src vector.

// destination vector
vector<float> dst;

I am currently using the source code below.

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());
}

In order to improve the speed of the copy, I tested the code below, but I only get a speedup of 5%. Why?

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);
}

How could further improve the speed of copying?

You should use vector::reserve() to avoid repeated reallocations and copying as you insert. And using reshape() shouldn't be necessary if it doesn't copy the data-- datastart and dataend are necessarily unchanged. Try this:

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM