`

一个个传入图片并统计像素点

 
阅读更多
//从文件夹中一张张传入图片,统计每张图片中白色像素点占比。累加和除以图片个数,算出平均值
#include <stdio.h>
#include "opencv2/highgui/highgui.hpp"  
#include "opencv2/imgproc/imgproc.hpp"  
#include "opencv2/core/core.hpp"
#include <opencv\ml.h>
#include <iostream>
#include "cv.h"
#include "highgui.h"
#include <vector>
#include <math.h>
#include <string.h>
#include <fstream>

using namespace std;
using namespace cv;

char filename[1000];
char windowname[1000];

int n = 0;//n是所有像素点
int counter = 0;//白色像素点

//计算一张图片的像素点
int bSums(Mat src)
{
	int black = 0;//黑色像素点
	
	//迭代器访问像素点
	Mat_<uchar>::iterator it = src.begin<uchar>();
	Mat_<uchar>::iterator itend = src.end<uchar>();
	for (; it != itend; ++it)
	{
		n++;
		if ((*it) > 0)
		{
			counter += 1;//二值化后,像素点是0或者255
		}
		else {
			black += 1;
		}
	}
	//白色像素点百分比
        double biliB = counter * 1.0 / n * 1.0 * 100 * 1.0;
        //黑色像素点百分比
	//double biliH = black * 1.0 / n * 1.0 * 100 * 1.0;
	//cout << "counter:" << counter << endl;
	//cout << "black:" << black << endl;
	//cout << "n:" << n << endl;
	//cout << "biliB:" << biliB << endl;
	//cout << "biliH:" << biliH << endl;
	return biliB;
}

int main(int argc, char *argv[])
{
	double sum = 0;
	double sumB = 0;
	int i;
        
        //循环传入图片
	for (i = 1; i <= 999; i++)
	{
                //文件夹中照片的名字必须从1开始
		sprintf_s(filename, "D://OK//%d.jpg", i);
		//sprintf(windowname, "window%d.jpg", i);
		Mat pScr = imread(filename, 1);

		//cvNamedWindow(windowname, CV_WINDOW_AUTOSIZE);
		//cvShowImage(windowname, pScr);
		Mat a1;
		cvtColor(pScr, a1, COLOR_BGR2GRAY);//转灰度图
		Mat a2;
		threshold(a1, a2, 0, 255, THRESH_BINARY | THRESH_OTSU);//二值化
		
		double B = bSums(a2);//调用函数bSums计算每张图片的白色像素点百分比
		sumB += counter;
		sum += B;//累加所有图片的白色像素点百分比

	}
	double per = sum * 1.0/ i *1.0;//除以图片个数,算出所有图片白色像素点百分比的平均值
	cout << "i: " << i << endl;
	cout << "sum: " << sum << endl;
	cout << "sumB: " << sumB << endl;
	cout << "per: " << per << endl;

	waitKey();
	system("pause");
	return 0;
}

 

 

分享到:
评论
发表评论

文章已被作者锁定,不允许评论。

相关推荐

Global site tag (gtag.js) - Google Analytics