Reputation: 3917
I have certain values in an std::vector<std::vector<double>>
structure of n rows and m cols which I would like to convert into an equivalent cv::Mat object. This is the code I have been using but I'm getting an error:
dctm is a local argument which is defined as:
std::vector<std::vector<double>>
cv::Mat dctmat = cvCreateMat(dctm.size(), dctm[0].size(), CV_16SC1);
for (size_t i = 0; i < dctm.size(); i++) {
for (size_t j = 0; j < dctm[i].size(); j++) {
dctmat.at<double>(i, j) = dctm[i][j];
}
}
Upvotes: 3
Views: 6429
Reputation: 41
Here is my templated version of conversion routines
routines
template<typename _Tp> static cv::Mat toMat(const vector<vector<_Tp> > vecIn) {
cv::Mat_<_Tp> matOut(vecIn.size(), vecIn.at(0).size());
for (int i = 0; i < matOut.rows; ++i) {
for (int j = 0; j < matOut.cols; ++j) {
matOut(i, j) = vecIn.at(i).at(j);
}
}
return matOut;
}
template<typename _Tp> static vector<vector<_Tp> > toVec(const cv::Mat_<_Tp> matIn) {
vector<vector<_Tp> > vecOut(matIn.rows);
for (int i = 0; i < matIn.rows; ++i) {
vecOut[i].resize(matIn.cols);
for (int j = 0; j < matIn.cols; ++j) {
vecOut[i][j] = matIn.at<_Tp>(i, j);
}
}
return vecOut;
}
Upvotes: 4
Reputation: 2426
Here in the Opencv documentation you can found this:
Mat::Mat(int rows, int cols, int type, void* data, size_t step=AUTO_STEP)
Mat::Mat(Size size, int type, void* data, size_t step=AUTO_STEP)
...
then, you can use like this:
Mat dctmat(dctm.size(), dctm[0].size(), CV_16SC1, dctm.data());
Upvotes: -4
Reputation: 2790
dctmat
has a type CV_16SC1
which means matrix of signed short. But you try to access it with dctmat.at<double>(i, j)
which is incoherent. Either define your matrix as CV_64FC1
or access it with dctmat.at<short>(i, j)
(first solution is better because you have a vector of double
).
Upvotes: 5