Reputation: 1023
I have a cv::Mat
but I have already inserted it with some values, how do I clear the contents in it?
Upvotes: 26
Views: 66264
Reputation: 21
You could always redeclare it if you want to empty the mat but keep using the variable. Idk if that's what you want but since the other answer to "clearing" a mat is .release() I'd just go to mention this.
Edit: My bad. I didn't realise how unclear my answer was. I was just answering the question of "how to clear a Mat variable of it's contents". Another person had answered that one can just do .release() to the variable, like for example, the person has a variable like
cv::Mat testMat;
and later on it's declared (as the question implied).
One person said that you could do a simple testMat.release()
. And if that's what op wants then there you go. But in the off chance that op just wants to clear the declaration of the variable, i just thought to mention that he/she could just re-declare it, like do a simple testMat = *some new information*
later on. Also, i mixed up define and declare. My bad
Upvotes: 0
Reputation: 60004
From the docs:
// sets all or some matrix elements to s
Mat& operator = (const Scalar& s);
then we could do
m = Scalar(0,0,0);
to fill with black pixels. Scalar has 4 components, the last - alpha - is optional.
Upvotes: 15
Reputation: 461
You can release
the current contents or assign a new Mat
.
Mat m = Mat::ones(1, 5, CV_8U);
cout << "m: " << m << endl;
m.release(); //this will remove Mat m from memory
//Another way to clear the contents is by assigning an empty Mat:
m = Mat();
//After this the Mat can be re-assigned another value for example:
m = Mat::zeros(2,3, CV_8U);
cout << "m: " << m << endl;
Upvotes: 4
Reputation: 5978
If you want to release the memory of the Mat
variable use release()
.
Mat m;
// initialize m or do some processing
m.release();
For a vector of cv::Mat
objects you can release the memory of the whole vector with myvector.clear()
.
std::vector<cv::Mat> myvector;
// initialize myvector ..
myvector.clear(); // to release the memory of the vector
Upvotes: 26
Reputation: 822
You should call release() function.
Mat img = Mat(Size(width, height), CV_8UC3, Scalar(0, 0, 0));
img.release();
Upvotes: 9