Created
December 4, 2020 09:58
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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