countNonZero():返回灰度值不为0的像素数,可用来判断图像是否全黑。
IplImage* srcImg = cvLoadImage("Lena.jpg");
//注意:当将参数copyData设为true后,则为深拷贝(复制整个图像数据)
Mat M(srcImg, true);
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <string>
using namespace cv;
void main()
{
cv::Mat image = imread("threshold.jpg");
cv::namedWindow("original");
cv::imshow("original",image);
string windowstring = "result 0";
string imagestring = "result 0.jpg";
cv::Mat result;
enum thresholdtype{THRESH_BINARY ,THRESH_BINARY_INV,THRESH_TRUNC,THRESH_TOZERO,THRESH_TOZERO_INV};
for (int thresh = 0;thresh<5;thresh++)
{
/* 0: 二进制阈值
1: 反二进制阈值
2: 截断阈值
3: 0阈值
4: 反0阈值
*/
threshold(image,result,150,255,thresholdtype(thresh));//改变参数实现不同的threshold
// 得到非0的像素值
int iVal255 = countNonZero(result);
cv::namedWindow(windowstring);
cv::imshow(windowstring,result);//显示输出结果
cv::imwrite(imagestring,result);
windowstring[7]++;
imagestring[7]++;
}
waitKey(0);
}
参考文章:
1. https://blog.youkuaiyun.com/zdyueguanyun/article/details/50857089