These two pieces of code:
A)
void KMeans<N>::assign_pixels_to_clusters()
{
for (auto cluster : clusters)
{
cluster.clear_pixels();
}
for (auto pixel : pixels)
{
float min_distance = FLT_MAX;
Cluster<N> c;
for (auto cluster : clusters)
{
float distance = norm(
pixel.get_value(),
cluster.get_centroid()
);
if (distance < min_distance)
{
min_distance = distance;
c = cluster;
}
}
c.add_pixel(pixel);
}
}
and B)
template <size_t N>
void KMeans<N>::assign_pixels_to_clusters()
{
for (auto cluster : clusters)
{
cluster.clear_pixels();
}
for (auto pixel : pixels)
{
float min_distance = FLT_MAX;
int idx = 0;
for (int i = 0; i < no_of_clusters; i++)
{
float distance = norm(
pixel.get_value(),
clusters[i].get_centroid()
);
if (distance < min_distance)
{
min_distance = distance;
idx = i;
}
}
clusters[idx].add_pixel(pixel);
}
}
seem similar to me, yet only B) works the way I want to. In the case of A), the pixels are not assigned to clusters at all. After the piece of code A) is run, the clusters are empty and have no pixels assigned to them. Can you help me understand why, please?