【Opencv】大律法求阈值+分割图像计算像素比

#include "opencv2/highgui/highgui.hpp"  
#include "opencv2/imgproc/imgproc.hpp"  
#include "opencv2/core/core.hpp"
#include <opencv\ml.h>
#include <iostream>
#include <vector>
#include <math.h>
#include <string.h>
using namespace std;
using namespace cv;;

//大津法求阈值
int otsu1(Mat frame) 
{
	 //frame灰度级
	int width=frame.rows;
	int	height=frame.cols;
	int pixelCount[256]={0};
	float pixelPro[256]={0};
	int i, j, pixelSum = width * height, threshold = 0;
	uchar* data = frame.data;
	float w0, w1, u0tmp, u1tmp, u0, u1, deltaTmp, deltaMax = 0;
	 //统计每个灰度级中像素的个数
	for(i = 0; i < height; i++)
	 {
	  for(j = 0;j < width;j++)
	  {
	   pixelCount[(int)data[i * width + j]]++;
	  }
	 }
	 //计算每个灰度级的像素数目占整幅图像的比例
	 for(i = 0; i < 256; i++)
	 {
	  pixelPro[i] = (float)pixelCount[i] / pixelSum;
	 }
	 //遍历灰度级[0,255],寻找合适的threshold
	 for(i = 0; i < 256; i++)
	 {
	  w0 = w1 = u0tmp = u1tmp = u0 = u1 = deltaTmp = 0;
	  for(j = 0; j < 256; j++)
	  {
	   if(j <= i)   //背景部分
	   {
		w0 += pixelPro[j];
		u0tmp += j * pixelPro[j];
	   }
	   else   //前景部分
	   {
		w1 += pixelPro[j];
		u1tmp += j * pixelPro[j];
	   }
	  }
	  u0 = u0tmp / w0;
	  u1 = u1tmp / w1;
	  deltaTmp = (float)(w0 *w1* pow((u0 - u1), 2)) ;
	  if(deltaTmp > deltaMax)
	  {
	   deltaMax = deltaTmp;
	   threshold = i;
	  }
	 }
	 return threshold;
}
//计算每个小块所占比例,存入向量
float Bili1(Mat src)
{
	
	float BL,counter = 0;
	int Sqaure = src.cols * src.rows;
	
	Mat_<uchar>::iterator it = src.begin<uchar>();
	Mat_<uchar>::iterator itend = src.end<uchar>();  
	for (; it!=itend; ++it)
	{
		if((*it)>0) counter+=1;
	}			
	BL = counter/Sqaure;
	return BL;
}
vector<float> Devide441(Mat img)
{
	//归一化,灰度化,二值化
	resize(img,img,Size(16,32));
	cvtColor(img,img,COLOR_BGR2GRAY);
	int th = otsu1(img);
	cv::threshold(img,img,th,255,THRESH_BINARY);
	
	//切割为4*4
	int a = img.cols/4; 
	int b = img.rows/4;
	vector<float> reback;
	for(int i = 0; i<4 ;++i)
	{
		for(int j = 0; j<4 ;++j)
		{	
			Rect roi_rect = Rect(Point(j*a,i*b),Size(a,b));
			Mat roi = img(roi_rect);
			float BL = Bili1(roi);

			reback.push_back(BL);
		}
	}
	return reback;

}



int main()
{
	Mat img1 = imread("train/7.bmp",1);
	imshow("img1",img1);
	vector<float> a = Devide441(img1);
	
	Mat A = Mat(a);
	cout<<A<<endl;

	Mat img2 = imread("LP8.jpg",1);
	imshow("img2",img2);
	vector<float> b = Devide441(img2);
	Mat B = Mat(b);
	cout<<B<<endl;

	waitKey();
	return 0;

}

-——————————————————————————————————————————————————————————————


  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值