OTSU算法

unsafe private int GetthreshValue(Bitmap img)
{
	BitmapData bd = img.LockBits(new Rectangle(0, 0, img.Width, img.Height), ImageLockMode.WriteOnly, img.PixelFormat);
	byte* pt = (byte*)bd.Scan0;
	int[] pixelNum = new int[256];
	byte color;
	byte* pline;
	int n, n1, n2;
	int total;
	double m1, m2, sum, csum, fmax, sb;
	int k, t, q;
	int threshValue = 1;
	int step = 1;
	switch (img.PixelFormat)
	{ 
		case PixelFormat.Format24bppRgb:
			step=3;
			break;
		case PixelFormat.Format32bppRgb:
			step = 4;
			break;
		case PixelFormat.Format8bppIndexed:
			step = 1;
			break;
	
	}
	//生成直方圖
	for (int i = 0; i < img.Height; i++)
	{
		pline = pt + i * bd.Stride;
		for (int j = 0; j < img.Width; j++)
		{
			color = *(pline + j * step);
			pixelNum[color]++;
		}
	}
	//直方圖平滑化
	for (k = 0; k <= 255; k++)
	{
		total = 0;
		for (t = -2; t <= 2; t++)
		{
			q = k + t;
			if (q < 0)
			{
				q = 0;
			}
			if (q > 255)
			{
				q = 255;
			}
			total = total + pixelNum[q];
		}
		pixelNum[k] = (int)((float)total / 5.0 + 0.5);
	}
	//求
	csum = 0;
	sum = csum;
	n = 0;
	for (k = 0; k <= 255; k++)
	{
		sum += (double)k * (double)pixelNum[k];
		n += pixelNum[k];
	}
	fmax = -1.0;
	n1 = 0;
	for (k = 0; k < 255; k++)
	{
		n1 += pixelNum[k];
		if (n1 == 0)
		{
			continue;
		}
		n2 = n - n1;
		if (n2 == 0)
		{
			break;
		}
		csum += (double)k * pixelNum[k];
		m1 = csum / n1;
		m2 = (sum - csum) / n2;
		sb = (double)n1 * (double)n2 * (m1 - m2) * (m1 - m2);
		if (sb > fmax)
		{
			fmax = sb;
			threshValue = k;
		}
	}
	img.UnlockBits(bd);
	
	return threshValue;
}

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