private void ClearData() { topColours = null; previousCluster = null; currentCluster = null; Histogram = null; Thresholds.Clear(); clusterArr.Clear(); converged = false; }
private void Iterate() { float d, curD; KeyValuePair <int, Cluster> closestCl = new KeyValuePair <int, Cluster>(); //find closest cluster for each histogram unit and apply info foreach (KeyValuePair <ushort, HistogramUnit> node in Histogram) { d = float.MaxValue; foreach (KeyValuePair <int, Cluster> c in currentCluster) { curD = Math.Abs(c.Value.Centroid - (float)node.Key); if (curD < d) { d = curD; closestCl = c; } } closestCl.Value.Counter += node.Value.Counter; closestCl.Value.Sum += node.Value.Sum; if (closestCl.Value.Min > node.Key) { closestCl.Value.Min = node.Key; } if (closestCl.Value.Max < node.Key) { closestCl.Value.Max = node.Key; } } //calculate the new centroids foreach (KeyValuePair <int, Cluster> c in currentCluster) { c.Value.Centroid = c.Value.Sum / c.Value.Counter; } //Calculate new thresholds clusterArr.Clear(); for (int i = 0; i < currentCluster.Count; i++) { Cluster tempClust = null; foreach (KeyValuePair <int, Cluster> cluster in currentCluster) { if (clusterArr.IndexOf(cluster.Value) == -1) { if (tempClust == null) { tempClust = cluster.Value; } else if (tempClust.Min > cluster.Value.Min) { tempClust = cluster.Value; } } } if (tempClust != null) { clusterArr.Add(tempClust); } } Thresholds.Clear(); for (int i = 0, j = 1; j < clusterArr.Count; i++, j++) { Thresholds.Add((int)(clusterArr[i].Max + ((clusterArr[j].Min - clusterArr[i].Max) / 2))); } Thresholds.Add(int.MaxValue); clusterArr.Clear(); //Clear; foreach (KeyValuePair <int, Cluster> c in currentCluster) { c.Value.Min = float.MaxValue; c.Value.Max = float.MinValue; c.Value.Counter = 1; c.Value.Sum = (long)c.Value.Centroid; } CheckConvergence(); }