enzom83
enzom83

Reputation: 8320

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?

Upvotes: 0

Views: 917

Answers (1)

John Zwinck
John Zwinck

Reputation: 249434

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

Upvotes: 1

Related Questions