C++ opencv 图片二值化最佳阈值确定(大津法,OTSU算法)

//opencv
#include "opencv2/opencv.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"

/******************************************************************************************
Function:       OtsuThreshold
Description:	图片二值化最佳阈值确定(大津法,OTSU算法)
Input:          src:原图片
Return:         阈值
******************************************************************************************/
int OtsuThreshold(IplImage* src)
{
	int threshold;

	try
	{
		int height = src->height;
		int width = src->width;

		//histogram  
		float histogram[256] = { 0 };
		for (int i = 0; i < height; i++) {
			unsigned char* p = (unsigned char*)src->imageData + src->widthStep*i;
			for (int j = 0; j < width; j++) {
				histogram[*p++]++;
			}
		}
		//normalize histogram  
		int size = height*width;
		for (int i = 0; i < 256; i++) {
			histogram[i] = histogram[i] / size;
		}

		//average pixel value  
		float avgValue = 0;
		for (int i = 0; i < 256; i++) {
			avgValue += i*histogram[i];
		}
		
		float maxVariance = 0;
		float w = 0, u = 0;
		for (int i = 0; i < 256; i++) {
			w += histogram[i];
			u += i*histogram[i];

			float t = avgValue*w - u;
			float variance = t*t / (w*(1 - w));
			if (variance > maxVariance) {
				maxVariance = variance;
				threshold = i;
			}
		}
	}
	catch (cv::Exception e)
	{
	}
	
	return threshold;
}

你可能感兴趣的:(C++,opencv)