convert openCV matrix into vector

2019-03-31 05:18发布

问题:

Looks deceptively easy. After all we know that an std or openCV vector can be easily converted into Matrix like this:

vector<Point> iptvec(10);
Mat iP(iptvec);

The reverse is suggested in openCV cheatSheet:

vector<Point2f> ptvec = Mat_ <Point2f>(iP);

However, there is one caveat: the matrix has to have only one row or one column. To convert an arbitrary matrix you have to reshape:

int sz = iP.cols*iP.rows;
vector<Point2f> ptvec = Mat <Point2f>(iP.reshape(1, sz));

Otherwise you will get an error:

*OpenCV Error: Assertion failed (dims == 2 && (sizes[0] == 1 || sizes[1] == 1 || sizes[0]*sizes[1] == 0)) in create, file /home/.../OpenCV-2.4.2/modules/core/src/matrix.cpp, line 1385...

回答1:

Create a 2dim vector and fill each row. E.g:

Mat iP=Mat::zeros(10, 20, CV_8UC1);
vector<vector<int>> ptvec;
for (int i = 0; i < iP.rows; i++)
{
    vector<int> row;    
    iP.row(i).copyTo(row);
    ptvec.push_back(row);
}