2

I have some problem with cv::Mat object. Output of the below code was wrong

void processFrame(const cv::Mat image, MyTracker& t)
{
    //some code
}

void main()
{
    MyTracker t;
    cv::VideoCapture(0);
    cv::Mat im , im_gray;
    while (true)
    {
         cap >> im; 
         cv::cvtColor(im, im_gray, CV_BGR2GRAY);
         processFrame(im_gray,t);
         cv::Rect r = t.bb_rot.boundingRect(); // get last bounding box of tracker 
         std::cout<<r.x<<"\t"<<r.y<<"\t"<<r.width<<"\t<<r.height;
    }
}

But when i use processFrame(im_gray.clone(),t); instead, solved the problem and result is correct. What is the problem that clone() function can solved this , however the first parameter of processFrame is const cv::Mat image and can't change in ProcessFrame.

I think image object will change in processFrame function

erfan zangeneh
  • 334
  • 1
  • 2
  • 10
  • the Mat header is const but not the pixel data. – Micka Apr 23 '16 at 20:13
  • 2
    Possible duplicate of [Differences of using "const cv::Mat &", "cv::Mat &", "cv::Mat" or "const cv::Mat" as function parameters?](http://stackoverflow.com/questions/23468537/differences-of-using-const-cvmat-cvmat-cvmat-or-const-cvmat) – herohuyongtao Apr 24 '16 at 16:09

1 Answers1

0

cv::Mat is a like a smart pointer. When you run the following code:

cv::Mat a = cv::Mat(...);
cv::Mat b = a;

You have two objects: a and b which points to the same data. The last one gets destructed will also free the memory. So in your case, you are not changing any of the values of the const matrix you get, you are changing the data, which is shared by all of them. When you use clone() method, you actually allocate a new data buffer and copy the data to it.

I hope it answers your question, you can read more here: cv::Mat docs

zenpoy
  • 19,490
  • 9
  • 60
  • 87
  • Tanks. But i don't understand why a const object will changed in function? – erfan zangeneh Apr 24 '16 at 05:04
  • 1
    The object itself is just metadata and a pointer to a buffer (the image data). The const means you can't change the metadata (size, type, etc.) but the data itself can get changed. – zenpoy Apr 24 '16 at 17:22