Created
September 10, 2022 06:48
-
-
Save arindas/443b0a7665166e15d8bd5664b985589b to your computer and use it in GitHub Desktop.
Maps a given image to the given palette. Image contains only colors from the given palette.
This file contains hidden or 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
| from textwrap import wrap | |
| from scipy.spatial import cKDTree | |
| from PIL import Image | |
| import numpy as np | |
| import matplotlib.pyplot as plt | |
| import argparse | |
| from pathlib import Path | |
| def hex_to_rgb(hex: str): | |
| return [int(x, 16) for x in wrap(hex.lstrip("#"), 2)] | |
| def map_image_to_palette(image, palette, loc=0, scale=0): | |
| gaussian = np.random.normal(loc, scale, size=image.shape).astype(np.uint8) | |
| image += gaussian | |
| palette = np.array(palette).astype(np.uint8) | |
| _, palette_indices = cKDTree(palette).query(image, k=1) | |
| image = palette[palette_indices] | |
| return image | |
| PALETTE = [ | |
| "#212121", | |
| "#303030", | |
| "#353535", | |
| "#4a4a4a", | |
| "#b2ccd6", | |
| "#eeffff", | |
| "#eeffff", | |
| "#ffffff", | |
| "#f07178", | |
| "#f78c6c", | |
| "#ffcb6b", | |
| "#c3e88d", | |
| "#89ddff", | |
| "#82aaff", | |
| "#c792ea", | |
| "#ff5370", | |
| ] | |
| PALETTE = [hex_to_rgb(x) for x in PALETTE] | |
| def main(args): | |
| print(args.file_path) | |
| path = Path(args.file_path) | |
| if not path.exists(): | |
| print("File not found!") | |
| return | |
| save_path = f"{path.parent}/{path.stem}-mapped{path.suffix}" | |
| image = Image.open(args.file_path) | |
| image = image.convert("RGB") | |
| image = np.array(image) | |
| mapped_image = map_image_to_palette(image, PALETTE) | |
| plt.imsave(save_path, mapped_image) | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser("Map color to palette.") | |
| parser.add_argument('file_path', metavar="FILE", | |
| type=str, | |
| help="Image to map to palette.") | |
| args = parser.parse_args() | |
| main(args) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment