chris d
chris d

Reputation: 79

OpenCv convert vector to matrix C++

I'm trying to convert a vector to (128*128)matrix using c++ opencv this is the code

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

the last row of the code is not correct but it just an example.

Upvotes: 1

Views: 10276

Answers (1)

Miki
Miki

Reputation: 41775

While the same question has been asked before and has been answered, e.g.:

I think a clear explanation of the obvious solution is still missing. Hence my answer.


OpenCV provides two easy ways to convert a std::vector to a cv::Mat, using Mat constructors:

You can either create a copy of the vector data (if you modify the vector, the data in the Mat will be unchanged), or create a Mat view of the content in the vector (if you modify the vector, the Mat will show the changes).

Please have a look at this code. First I create a random Mat of double that I copy in a vector. Then apply some function that accepts this vector and returns a new one. This was only to align the code to your requirements. Then you can see how to get a cv::Mat from a std::vector, with or without copying the data.

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

Upvotes: 9

Related Questions