本文主要是介绍一个个传入图片(二值化后)并统计像素点,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
//从文件夹中一张张传入图片,统计每张图片中白色像素点占比。累加和除以图片个数,算出平均值
#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;
}
这篇关于一个个传入图片(二值化后)并统计像素点的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!