OpenCV計算指定區域的黑白像素個數

過程模擬模板匹配過程,可修改成模板匹配方式:
過程:讀取一張圖片->從圖片中選取感興趣區域(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);
}

結果:

黑白區域結果:

在這裏插入圖片描述
全黑區域結果:
在這裏插入圖片描述
全白區域結果:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章