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