Skip to content

Instantly share code, notes, and snippets.

@syaffers
Created December 4, 2020 10:10
Show Gist options
  • Save syaffers/b88bba24cce8dd59e7ff0156b0a922cb to your computer and use it in GitHub Desktop.
Save syaffers/b88bba24cce8dd59e7ff0156b0a922cb to your computer and use it in GitHub Desktop.
Modified recolor function with a better color distance
class EntirePalette:
# ... omitted
def recolor(self, image):
image_shape = image.shape
image = self._preprocess(image)
image_colors = np.unique(image, axis=0)
self_da = da.from_array(
self.source_pixels.astype(np.long), chunks=(self.chunk_size, 3)
)
other_da = da.from_array(
image_colors.reshape(-1, 1, 3).astype(np.long),
chunks=(self.chunk_size, 1, 3)
)
# Perceptually "better" color distance.
rmean_da = (other_da[:, :, 0] + self_da[:, 0]) // 2
rgb_da = other_da - self_da
r_da = ((512 + rmean_da) * rgb_da[:, :, 0] ** 2) >> 8
g_da = 4 * rgb_da[:, :, 1] ** 2
b_da = ((767 - rmean_da) * rgb_da[:, :, 2] ** 2) >> 8
result_da = (r_da + g_da + b_da).argmin(axis=1)
with ProgressBar():
mapping_idx = idxs_da.compute()
colormap = {tuple(a): tuple(b)
for a, b in
zip(image_colors, self.source_colors[mapping_idx])}
image_recolored = np.array([colormap[tuple(rgb)] for rgb in image])
return image_recolored.reshape(image_shape).astype(np.uint8)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment