C++ 如何清除 cv::Mat 内容?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16817263/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 20:40:22  来源:igfitidea点击:

How to clear the cv::Mat contents?

c++opencv

提问by anarchy99

I have a cv::Matbut I have already insert it with some values, how do I clear the contents in it?

我有一个cv::Mat但我已经插入了一些值,如何清除其中的内容?

Thank you

谢谢

回答by Alexey

If you want to release the memory of the Matvariable use release().

如果要释放Mat变量的内存,请使用release().

Mat m;
// initialize m or do some processing
m.release();

For a vector of cv::Matobjects you can release the memory of the whole vector with myvector.clear().

对于cv::Mat对象向量,您可以使用 释放整个向量的内存myvector.clear()

std::vector<cv::Mat> myvector;
// initialize myvector .. 

myvector.clear(); // to release the memory of the vector

回答by CapelliC

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.

填充黑色像素。标量有 4 个分量,最后一个 - alpha - 是可选的。

回答by Poko

You should call release() function.

您应该调用 release() 函数。

 Mat img = Mat(Size(width, height), CV_8UC3, Scalar(0, 0, 0));
 img.release();

回答by abggcv

You can releasethe current contents or assign a new Mat.

您可以release将当前内容或分配一个新的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;