Skip to content

Instantly share code, notes, and snippets.

@syaffers
Created December 4, 2020 09:58
Show Gist options
  • Save syaffers/172137f3f8be29cc1b06e49bbc4ae739 to your computer and use it in GitHub Desktop.
Save syaffers/172137f3f8be29cc1b06e49bbc4ae739 to your computer and use it in GitHub Desktop.
Modified fit function to precalculate the distances of pixels to the nearest centroid
class KMeansReducedPalette:
# ... omitted
def fit(self, image):
image_cpy = image.copy()
self.source_pixels = self._preprocess(image_cpy)
self.kmeans.fit(self.source_pixels)
self.centroid_nearest_pixels = []
for ci in range(self.num_colors):
pixels_ci = self.source_pixels[self.kmeans.labels_ == ci]
distances_ci = np.sqrt(np.sum(np.square(
pixels_ci - self.kmeans.cluster_centers_[ci]), axis=1))
pixels_ci = pixels_ci[np.argsort(distances_ci)]
self.centroid_nearest_pixels.append(pixels_ci)
# ... omitted
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment