opencv 二值化图像 像素统计 countNonZero

对二值化图像执行countNonZero。可得到非零像素点数.

IplImage* srcImg = cvLoadImage("Lena.jpg");

//注意:当将参数copyData设为true后,则为深拷贝(复制整个图像数据)
Mat M(srcImg, true);

#include 
#include 
#include 
#include 

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);
}

程序结果:

threshold.jpg(源图像)

THRESH_BINARY(二进制阈值)

 

THRESH_BINARY_INV(反二进制阈值)

 THRESH_TRUNC(截断阈值)

  

 THRESH_TOZERO(0阈值)

 

THRESH_TOZERO_INV(反0阈值)

 


你可能感兴趣的:(opencv,Mat,IplImage,opencv)