opencv实现otsu算法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/love_image_xie/article/details/87641345
int OTSU(Mat src)
{
	int col = src.cols;
	int row = src.rows;
	int threshold = 0;
	//初始化统计参数
	int nSumPix[256];//每个像素值的数目
	float nProDis[256];
	for (int i = 0; i < 256; i++)
	{
		nSumPix[i] = 0;
		nProDis[i] = 0;
	}
	//统计灰度级中每个像素在整幅图像中的个数
	for (int i = 0; i < col; i++)
	{
		for (int j = 0; j < row; j++)
		{
			nSumPix[(int)src.at<uchar>(i, j)]++;
		}
	}
	//计算每个灰度级占图像中的概率分布
	for (int i = 0; i < 256; i++)
	{
		nProDis[i] = (float)nSumPix[i] / (col*row);
	}
	//w0前景点所占比例,u0前景点灰度均值
	float w0, w1, u0, u1, u0_temp, u1_temp, delta_temp;
	double delta_max = 0;
	for (int i = 0; i < 256; i++)
	{
		//i表示前景点,即分割阈值,j表示背景点
		//初始化相关参数
		w0 = w1 = u0_temp = u1_temp = u0 = u1 = delta_temp = 0;
		for (int j = 0; j < 256; j++)
		{
			if (j <= i)
			{
				w0 += nProDis[j];
				u0_temp += j*nProDis[j];
			}
			else
			{
				w1 += nProDis[j];
				u1_temp += j*nProDis[j];
			}
		}
		//各类平均灰度
		u0 = u0_temp / w0;
		u1 = u1_temp / w1;
		delta_temp = (float)(w0*w1*pow((u0-u1),2));
		if (delta_temp > delta_max)
		{
			delta_max = delta_temp;
			threshold = i;
		}
	}
	return threshold;
}

猜你喜欢

转载自blog.csdn.net/love_image_xie/article/details/87641345
今日推荐