Reputation: 5
I am trying to use OpenCV in Windows Form. I created a global cv::Mat object and is expecting the object for other functions to use. However every time I initialized the global cv::Mat object and quit/return the function, the values of my global cv::Mat object will change automatically with unknown reason.
One sample code snippet is like:
private: cv::Mat *cvImage;
For some reason, I created a function called decode() which returns cv::Mat.
void copy(){cvImage = &decode();}
the cvImage cannot get the correct values by the above codes. Usually is data, dataend, datalimit, datastart and rows being 0 or unexpected values.
Even I tried to use a local variable, say cv::Mat img, to do everything then run cvImage = &img;
, whenever the function quits or returns, the value of cvImage will also change unexpectedly.
I am wondering why would this happen??
Upvotes: 0
Views: 2264
Reputation: 39796
your use of pointers there creates undefined behaviour. don't use them with Mats !
DONT cv::Mat *cvImage;
DO cv::Mat cvImage;
cv::Mats are refcounted, those pointers will wreck havoc on them.
as a reminder:
Mat a,b; b=a; // shallow copy, shared pixels (that's probably, what you wanted)
Mat a,b; b=a.clone(); // deep copy, b will have y copy of a's pixels
Edit:
"For some reason, I created a function called decode() which returns cv::Mat."
that's your first problem here decode creates a temporary( which gets destroyed after leaving copy() )
void copy(){cvImage = &decode();}
and you return the address of it.
since it seems, that cli can handle only POD objects(like pointers)
let decode return a a Mat*, instead of taking the address of a temp
Mat * decode() { Mat *m = new Mat(100,100,CV_UC8); ... return m; }
let copy dlete the old one
void copy(){ if (cvImage) delete cvImage; cvImage = decode(); }
Upvotes: 2