繁体   English   中英

OpenCv将向量转换为矩阵C ++

[英]OpenCv convert vector to matrix C++

我正在尝试使用C ++ OpenCV将向量转换为(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 ,则Mat的数据将保持不变),也可以创建矢量中内容的Mat 视图 (如果您修改vector ,则Mat将显示变化)。

请看一下这段代码。 首先,我创建一个随机的Double Mat ,将其复制到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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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