Skip to content

Instantly share code, notes, and snippets.

@syaffers
Created December 4, 2020 09:52
Show Gist options
  • Save syaffers/7b8fcee5d84aa6031694d3adb4c67fad to your computer and use it in GitHub Desktop.
Save syaffers/7b8fcee5d84aa6031694d3adb4c67fad to your computer and use it in GitHub Desktop.
Random walk recolor method of the reduced palette class
class KMeansReducedPalette:
# ... omitted
def random_walk_recolor(self, image, max_steps):
original_shape = image.shape
image = self._preprocess(image)
centroids = self.kmeans.predict(image)
start = np.round(self.kmeans.cluster_centers_[centroids])
diff = np.zeros(image.shape)
for _ in range(max_steps):
walk = np.eye(3)[np.random.randint(0, 3, size=image.shape[0])]
sign = np.random.choice([-1, 1], size=(image.shape[0], 1))
diff += walk * sign
recolor = np.clip(start + diff, 0, 255).astype(np.uint8)
return recolor.reshape(original_shape)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment