过程模拟模板匹配过程,可修改成模板匹配方式:
过程:读取一张图片->从图片中选取感兴趣区域(ROI),并保存->把保存下来的区域图片(ROI)读取出来->预处理后计算黑白像素的个数
#include "stdafx.h"
#include "opencv2/highgui/highgui.hpp"
#include "cv.h"
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
using namespace std;
using namespace cv;
//黑白像素个数统计
int PixelCounter(Mat src, int nflag)
{
int nCount_White = 0;//白
int nCount_Black = 0;//黑
//通过迭代器访问图像的像素点
Mat_<uchar>::iterator itor = src.begin<uchar>();
Mat_<uchar>::iterator itorEnd = src.end<uchar>();
for (; itor != itorEnd; ++itor)
{
if ((*itor) > 0)
{
//白:像素值 ptr:255
nCount_White += 1;
}
else
{
//黑:像素值 ptr:0
nCount_Black += 1;
}
}
//根据nflag返回黑或白像素个数
if (nflag == 1)
{
//白
return nCount_White;
}
else
{
//黑
return nCount_Black;
}
}
void main()
{
//读取图片
Mat imgSrc = imread("Pic.bmp");
//选取的区域【根据实际可改为动态区域】
//Rect rect(150, 180, 110, 100);//黑白区域
//Rect rect(10, 10, 110, 100);//全黑区域
Rect rect(180, 200, 50, 50);//全白区域
//显示选取的区域
Mat image_roi = imgSrc(rect);
imshow("选取的区域", image_roi);
//保存感兴趣区域
imwrite("ImgROI.bmp", image_roi);
//在源图上框选出roi区域
rectangle(imgSrc, rect, Scalar(255, 0, 0), 3);//根据实际修改缩放比例
imshow("原图", imgSrc);
//-----------------------------------
//读取保存的图片(感兴趣区域)
static string imgTemp = "ImgROI.bmp";
Mat temp = imread(imgTemp);
//转成灰度图
cvtColor(temp, temp, COLOR_BGR2GRAY);
//二值化
threshold(temp, temp, 200, 255, THRESH_BINARY);
//计算白像素个数
int nWhiteCount = PixelCounter(temp, 1);
//计算黑像素个数
int nBlackCount = PixelCounter(temp, 2);
//输出
printf("像素个数统计:\n");
printf("\n白像素:%d\n黑像素:%d\n总像素:%d\n", nWhiteCount, nBlackCount, (nBlackCount + nWhiteCount));
waitKey(0);
}
结果:
黑白区域结果:
全黑区域结果:
全白区域结果: