BrandSmith / src /graphics_tools.py
raznis's picture
Upload folder using huggingface_hub
c9f5fa7 verified
from PIL import Image
from templates import image_template, example_templates
def find_closest_color_idx(color, template_colors):
return min(enumerate(template_colors), key=lambda template_color: compute_difference(color, template_color[1]))[0]
def compute_difference(color1, color2):
return abs(color1[0] - color2[0]) + abs(color1[1] - color2[1]) + abs(color1[2] - color2[2])
def replace_colors_by_template(image_template: image_template.ImageTemplate, target_colors: list[tuple[int, int, int]]):
"""Replaces colors in the template image based on the closest color difference.
Args:
image_template: ImageTemplate object
target_colors: List of RGB tuples for the target colors
Returns:
PIL Image object
"""
img = Image.open(image_template.image).convert("RGB")
pixels = img.load()
width, height = img.size
for x in range(width):
for y in range(height):
closest_color_idx = find_closest_color_idx(pixels[x, y], image_template.colors)
pixels[x, y] = target_colors[closest_color_idx]
return img
# Example usage
if __name__ == "__main__":
target_colors = [(212,233,225), (46,98,67), (252,254,252)]
image_template = example_templates.get_three_color_template()
img = replace_colors_by_template(image_template, target_colors)
img.save("output/modified_image.jpg")