gpt4 book ai didi

c++ - OpenCv 将 vector 转换为矩阵 C++

转载 作者:太空宇宙 更新时间:2023-11-03 10:26:01 25 4
gpt4 key购买 nike

我正在尝试使用 C++ opencv 将 vector 转换为 (128*128) 矩阵这是代码

Mat image = imread("1.jpg", 0);
vector<double> vec ImgVec[i].assign(image.datastart, image.dataend);
vector<double> avgFace = calAvgFace(vec);
Mat img=avgFace;

代码的最后一行不正确,但它只是一个示例。

最佳答案

虽然之前已经问过同样的问题并且已经回答过,例如:

我认为仍然缺少对明显解决方案的明确解释。因此我的答案。


OpenCV 提供了两种使用 Mat 构造函数将 std::vector 转换为 cv::Mat 的简单方法:

您可以创建 vector 数据的拷贝(如果您修改vectorMat 中的数据将保持不变),或者创建一个 vector 中内容的 Mat View (如果修改 vectorMat 将显示更改)。

请看一下这段代码。首先,我创建了一个 double 的随机 Mat,并将其复制到 vector 中。然后应用一些接受这个 vector 并返回一个新 vector 的函数。这只是为了使代码符合您的要求。然后您可以看到如何从 std::vector 获取 cv::Mat,有或没有复制数据。

#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;

vector<double> foo(const vector<double>& v)
{
// Apply some operation to the vector, and return the result

vector<double> result(v);
sort(result.begin(), result.end());
return result;
}

int main()
{
// A random CV_8UC1 matrix
Mat1d dsrc(128,128);
randu(dsrc, Scalar(0), Scalar(1));

imshow("Start double image", dsrc);
waitKey();

// Get the vector (makes a copy of the data)
vector<double> vec(dsrc.begin(), dsrc.end());

// Apply some operation on the vector, and return a vector
vector<double> res = foo(vec);

// Get the matrix from the vector

// Copy the data
Mat1d copy_1 = Mat1d(dsrc.rows, dsrc.cols, res.data()).clone();

// Copy the data
Mat1d copy_2 = Mat1d(res, true).reshape(1, dsrc.rows);

// Not copying the data
// Modifying res will also modify this matrix
Mat1d no_copy_1(dsrc.rows, dsrc.cols, res.data());

// Not copying the data
// Modifying res will also modify this matrix
Mat1d no_copy_2 = Mat1d(res, false).reshape(1, dsrc.rows);


imshow("Copy 1", copy_1);
imshow("No Copy 1", no_copy_1);
waitKey();

// Only no_copy_1 and no_copy_2 will be modified
res[0] = 1.0;

imshow("After change, Copy 1", copy_1);
imshow("After change, No Copy 1", no_copy_1);
waitKey();

return 0;
}

关于c++ - OpenCv 将 vector 转换为矩阵 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35146631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com