Ask Your Question
0

Why mat.ptr<>() has the same address among all the elements inside std::vector<cv::Mat>?

asked 2017-11-25 03:55:28 -0600

updated 2017-11-25 03:58:49 -0600

If I construct outfea_ in the following manner, then you'll find the three output have exactly the same value. Is it a bug in opencv?

std::vector<cv::Mat> outfea_(3, cv::Mat(5, 5, CV_32FC1, cv::Scalar(0)));
cout<< outfea_.at(0).ptr<float>(0)<<endl;
cout<< outfea_.at(1).ptr<float>(0)<<endl;
cout<< outfea_.at(2).ptr<float>(0)<<endl;
edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
0

answered 2017-11-25 04:14:14 -0600

berak gravatar image

updated 2017-11-25 04:22:12 -0600

this is, because all the Mat's in your vector really point to the same data !

the vector constructor makes a "shallow" copy of the Mat argument only, so they all share the same data ptr.

(this is not restricted to cv::Mat, you'll see that with anything, that contains a pointer, the vector makes shallow copies of the pointer, not whatever it points to)

the only remedy is to fill the vector with independant Mat's like:

// c++11
std::vector<cv::Mat> outfea_ = {
 cv::Mat(5, 5, CV_32FC1, cv::Scalar(0)),
 cv::Mat(5, 5, CV_32FC1, cv::Scalar(0)),
 cv::Mat(5, 5, CV_32FC1, cv::Scalar(0))
};

 // c++98
std::vector<cv::Mat> outfea_; 
for (int i=0;i<3; i++) {
 outfea_.push_back(cv::Mat(5, 5, CV_32FC1, cv::Scalar(0)));
}
edit flag offensive delete link more

Comments

Oh I got it, thanks a lot!

charlesjiangxm gravatar imagecharlesjiangxm ( 2017-11-25 05:12:16 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2017-11-25 03:55:28 -0600

Seen: 340 times

Last updated: Nov 25 '17