加载图像:
k聚类分割后图像,分成黑白两类,故意把结果黑色类染红,核对发现是正确的:
具体算法如下:
float globu1 = 40;
float globu2 = 180;
public void k均值迭代法更新(int imgw, int imgh, byte[] img)
{
//1,归类
List<Point> QArea1 = new List<Point>();
List<Point> QArea2 = new List<Point>();
for (int i = 0; i < imgw; i++)
for (int j = 0; j < imgh; j++)
{
int pos = j * imgw + i;
if (Math.Abs(img[pos] - globu1) - Math.Abs(img[pos] - globu2) < 0)
{
Point tempt = new Point(i, j);
QArea1.Add(tempt);
}
else
{
Point tempt = new Point(i, j);
QArea2.Add(tempt);
}
}
//2,更新均值
float u1 = 0; float u2 = 0;
for (int i = 0; i < QArea1.Count; i++)
{
int pos = QArea1[i].Y * imgw + QArea1[i].X;
u1 += img[pos];
}
for (int i = 0; i < QArea2.Count; i++)
{
int pos = QArea2[i].Y * imgw + QArea2[i].X;
u2 += img[pos];
}
u1 = u1 / QArea1.Count;
u2 = u2 / QArea2.Count;
if (Math.Abs(globu1 - u1) < 2 || Math.Abs(globu2 - u2) < 2)
{
return;
}
else
{
globu1 = u1;
globu2 = u2;
k均值迭代法更新(imgw, imgh, img);
}
}