Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenCV vector to Mat but not element->row

There is a very simple way to construct a Mat from a vector...just by doing:

vector<int> myVector;
Mat myMatFromVector(myVector,true); //the boolean is to define if you want to copy the data

The problem with this contructor is that each vector's element will be placed in each row of the Matrix. What I want is each element of my vector to be placed in each column of the matrix.

As is:
vector<int> = [1,2,3,4]
Matrix = [1;2;3;4]

I want:
vector<int> = [1,2,3,4]
Matrix = [1,2,3,4]
like image 750
out_sid3r Avatar asked Nov 17 '25 05:11

out_sid3r


2 Answers

Either specify the shape and type of the Matrix and pass the vector data

   // constructor for matrix headers pointing to user-allocated data
    Mat(int _rows, int _cols, int _type, void* _data, size_t _step=AUTO_STEP);
    Mat(Size _size, int _type, void* _data, size_t _step=AUTO_STEP);

Or call reshape on the Mat to swap the number of row sand columns ( doesn't change any data)

    // creates alternative matrix header for the same data, with different
    // number of channels and/or different number of rows. see cvReshape.
    Mat reshape(int _cn, int _rows=0) const;
like image 200
Martin Beckett Avatar answered Nov 20 '25 09:11

Martin Beckett


The matrix formed by reflecting a matrix through its main diagonal (ie interchanging the rows and columns) is called the transpose. Using OpenCV, you can easily obtain the transpose of a matrix A as:

Mat A;
Mat A_transpose = A.t();

If A is [1; 2; 3; 4], A_transpose will be [1, 2, 3, 4] as required.

So, you could either create a transposed copy of your matrix after converting it from the vector, or you could create it easily when subsequently required in your calculations.

Mat A, B;
Mat answer = A.t() * B;
like image 41
Chris Avatar answered Nov 20 '25 08:11

Chris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!