Mat::col() to std::vector bug?
I'm trying to convert a column of a cv::Mat
to an std::vector
. Mat has such a type conversion operator but it doesn't do what I would expect. Let's create a 10 by 2 matrix and add ascending elements in row major order starting with 1.
cv::Mat m(10,2, CV_64F);
int num = 1;
for (int row = 0; row < m.rows; ++row)
{
for (int col = 0; col < m.cols; ++col)
{
m.at<double>(row,col) = (double)(num++);
}
}
std::vector<double> v = m.col(0);
cout << v[0] << endl; //outputs 1, OK
cout << v[1] << endl; //outputs 0 instead of 3
cout << v[2] << endl; //outputs 0 instead of 5, etc.
However, if I replace the line
std::vector<double> v = m.col(0);
with
std::vector<double> v = m.col(0).clone();
then it works as expected and outputs lines 1, 3, 5.
With some other matrix sizes (e.g. 120x2) it even crashes at memcpy
(inside cv::Mat::copyTo(cv::OutputArray)
) with segmentation fault or at vector destruction.
I'm using OpenCV 2.4.8 Debug build, GCC 4.8.2, Ubuntu 14.04 LTS 64-bit.