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

chr*_*s d 1 c++ opencv image vector matrix

我正在尝试使用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;
Run Code Online (Sandbox Code Playgroud)

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

Mik*_*iki 8

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

我认为对这一明显解决方案的明确解释仍然缺失.因此我的答案.


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

您可以创建矢量数据的副本(如果您修改vector,则数据Mat将保持不变),或者在矢量中创建内容Mat 视图(如果您修改了vector,Mat将显示更改).

请看一下这段代码.首先,我创建一个Mat双重随机,我复制在一个vector.然后应用一些接受此向量的函数并返回一个新函数.这只是为了使代码符合您的要求.然后你可以看到如何cv::Mat从a std::vector,有或没有复制数据.

#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;
}
Run Code Online (Sandbox Code Playgroud)