简体   繁体   中英

OpenCV 2.3.1. cv::Mat to std::vector cast


I do have a trouble converting cv::Mat to std::vector:

cv::Mat m = cv::Mat_<int>::eye(3, 3);    
std::vector<int> vec = m;

gives me the following:

OpenCV Error: Assertion failed (dims == 2 && (size[0] == 1 || size[1] == 1 || size[0]*size[1] == 0)) in create, file /build/buildd-opencv_2.3.1-11-i386-tZNeKk/opencv-2.3.1/modules/core/src/matrix.cpp, line 1225
terminate called after throwing an instance of 'cv::Exception'
  what():  /build/buildd-opencv_2.3.1-11-i386-tZNeKk/opencv-2.3.1/modules/core/src/matrix.cpp:1225: error: (-215) dims == 2 && (size[0] == 1 || size[1] == 1 || size[0]*size[1] == 0) in function create

from mat.hpp:

template<typename _Tp> inline Mat::operator vector<_Tp>() const
{
    vector<_Tp> v;
    copyTo(v);
    return v;
}

and later on the following code in copyTo is executed:

//mat.hpp 
template<typename _Tp> inline _OutputArray::_OutputArray(vector<_Tp>& vec) : _InputArray(vec) {}

template<typename _Tp> inline _InputArray::_InputArray(const vector<_Tp>& vec)
    : flags(STD_VECTOR + DataType<_Tp>::type), obj((void*)&vec) {}

// operations.hpp
template<typename _Tp> inline Size_<_Tp>::Size_()
    : width(0), height(0) {}

and then I get an exceptions.

Any idea? Is it a bug? Probably, I do not understand something... Thank You in advance!

It seems like you are trying to convert a two-dimensional 3x3 matrix into a one-dimensional vector. Not sure what result you're expecting from that, but you probably want to convert a row of the matrix into a vector. You can use this by giving the vector constructor a pointer to the row data:

int *p = eye.ptr<int>(0); // pointer to row 0
std::vector<int> vec(p, p+eye.cols); // construct a vector using pointer

Very Well Then!

cv::Mat is stored as an array of bytes!
So, if You want to represent your matrix as vector, You may do something like this:

cv::Mat m = cv::Mat_<int>::eye(3, 3);
int* data = reinterpret_cast<int*>(m.data);
int len = m.rows * m.cols;
std::vector<int> vec(len);
std::copy(data + 0, data + len, vec.begin());

From the error message, it looks like you can only convert matrices where one dimension is 1 to std::vector , ie only row or column vectors (mathematically speaking):

dims == 2 && (size[0] == 1 || size[1] == 1)

Which kind of makes sense...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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