Vector cv :: Mat are interconnected

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 he 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 initialization of the vector be inline.

0
source share
1 answer

You cannot do this. The constructor vectoruses a copy constructor Matthat copies only the header, not the data. You need to explicitly use clone()somehow or create a new matrix every time: for example:

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(); });
0
source

Source: https://habr.com/ru/post/1673828/


All Articles