using System;
namespace Splash.Imaging
{
/// <summary>
/// 图像处理:迭代法二值化阈值计算方法
/// </summary>
public static partial class Binarize
{
/// <summary>
/// 迭代法计算阈值
/// </summary>
/// <param name="grayArray">灰度数组</param>
/// <returns>二值化阈值</returns>
public static Int32 IterativeThreshold(Byte[,] grayArray)
{ // 建立统计直方图
Int32[] Histogram = new Int32[256];
Array.Clear(Histogram, 0, 256); // 初始化
foreach (Byte b in grayArray)
{
Histogram[b]++; // 统计直方图
}
// 总的质量矩和图像点数
Int32 SumC = grayArray.Length; // 总的图像点数
Int32 SumU = 0;
for (Int32 i = 1; i < 256; i++)
{
SumU += i * Histogram[i]; // 总的质量矩
}
// 确定初始阈值
Int32 MinGrayLevel = Array.FindIndex(Histogram, NonZero); // 最小灰度值
Int32 MaxGrayLevel = Array.FindLastIndex(Histogram, NonZero); // 最大灰度值
Int32 T0 = (MinGrayLevel + MaxGrayLevel) >> 1;
if (MinGrayLevel != MaxGrayLevel)
{
for (Int32 Iteration = 0; Iteration < 100; Iteration++)
{ // 计算目标的质量矩和点数
Int32 U0 = 0;
Int32 C0 = 0;
for (Int32 i = MinGrayLevel; i <= T0; i++)
{ // 目标的质量矩和点数
U0 += i * Histogram[i];
C0 += Histogram[i];
}
// 目标的平均灰度值和背景的平均灰度值的中心值
Int32 T1 = (U0 / C0 + (SumU - U0) / (SumC - C0)) >> 1;
if (T0 == T1) break; else T0 = T1;
}
}
// 返回最佳阈值
return T0;
}
}
}
WPF:图像处理(五)迭代法
最新推荐文章于 2024-01-08 01:28:12 发布