C++ 如何确定 cv::Mat 是否为零矩阵?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13907574/
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 17:49:10  来源:igfitidea点击:

How to determine if a cv::Mat is a zero matrix?

c++opencvmatrixcompare

提问by JM92

I have a matrix that is dynamically being changed according to the following code;

我有一个根据以下代码动态更改的矩阵;

 for( It=all_frames.begin(); It != all_frames.end(); ++It)
{
    ItTemp = *It;

    subtract(ItTemp, Base, NewData);

    cout << "The size of the new data for ";
    cout << " is \n" << NewData.rows << "x" << NewData.cols << endl;
    cout << "The New Data is: \n" << NewData << endl << endl;

    NewData_Vector.push_back(NewData.clone());

}

What I want to do is determine the frames at which the cv::Mat NewData is a zero matrix. I've tried comparing it to a zero matrix that is of the same size, using both the cv::compare() function and simple operators (i.e NewData == NoData), but I can't even compile the program.

我想要做的是确定 cv::Mat NewData 为零矩阵的帧。我尝试将它与大小相同的零矩阵进行比较,同时使用 cv::compare() 函数和简单的运算符(即 NewData == NoData),但我什至无法编译程序。

Is there a simple way of determining when a cv::Mat is populated by zeroes?

有没有一种简单的方法可以确定 cv::Mat 何时填充零?

回答by JM92

I used

我用了

if (countNonZero(NewData) < 1) 
{
    cout << "Eye contact occurs in this frame" << endl;
}

This is a pretty simple (if perhaps not the most elegant) way of doing it.

这是一种非常简单(如果可能不是最优雅的)的方法。

回答by tomriddle_1234

To check the mat if is empty, use empty(), if NewData is a cv::Mat, NewData.empty()returns true if there's no element in NewData.

要检查 mat 是否为空,请使用empty(),如果 NewData 是 cv::Mat,NewData.empty()如果 NewData 中没有元素,则返回 true。

To check if it's all zero, simply, NewData == Mat::zeros(NewData.size(), NewData.type()).

要检查它是否全部为零,只需,NewData == Mat::zeros(NewData.size(), NewData.type()).

Update:

更新:

After checking the OpenCV source code, you can actually do NewData == 0to check all element is equal to 0.

检查 OpenCV 源代码后,您实际上NewData == 0可以检查所有元素是否等于 0。

回答by malli

countNonZero(Mat ) will give u number of non zeros in mat

countNonZero(Mat ) 将在 mat 中给出 u 个非零值

回答by David Gatti

The Mat object has an emptyproperty, so you can just ask Mat to tell you if it has something or it's empty. The result will be either trueor false.

Mat 对象有一个属性,所以你可以让 Mat 告诉你它是否有东西或者它是空的。结果将是truefalse

回答by Spaceghost

How about this..

这个怎么样..

Mat img = Mat::zeros(cvSize(1024, 1024), CV_8UC3);
bool flag = true;

MatConstIterator_<double> it = img.begin<double>();
MatConstIterator_<double> it_end = img.end<double>();
for(; it != it_end; ++it)
{
    if(*it != 0)
    {
        flag = false;
        break;
    }
}