Vector of cv::Mat are linked between them

2019-09-14 19:21发布

问题:

std::vector<cv::Mat1f> mat = std::vector<cv::Mat1f>(10,cv::Mat1f::zeros(1,10));
mat[0]+=1;
for(size_t i=0;i<mat.size();i++)
    std::cout<<mat[i]<<std::endl;

And it prints:

[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

How can I avoid this? It would be very important that the vector initialization is inline.

回答1:

You can't do that. The vector constructor uses the Mat copy constructor, which only copies the header but not the data. You need to explicitly use clone() somehow, or create a new matrix every time: E.g:

std::vector<cv::Mat1f> mat(10);
for (size_t i = 0; i < mat.size(); i++) {
    mat[i] = cv::Mat1f(1, 10, 0.f);
}

or:

cv::Mat1f m = cv::Mat1f(1, 10, 0.f);
std::vector<cv::Mat1f> mat(10);
for (size_t i = 0; i < mat.size(); i++) {
    mat[i] = m.clone();
}

or:

std::vector<cv::Mat1f> mat(10);
std::generate(mat.begin(), mat.end(), []() {return cv::Mat1f(1, 10, 0.f); });

or:

cv::Mat1f m = cv::Mat1f(1, 10, 0.f);
std::vector<cv::Mat1f> mat(10);
std::generate(mat.begin(), mat.end(), [&m]() {return m.clone(); });