Skip to content

Instantly share code, notes, and snippets.

@Aareon
Created July 1, 2017 17:58
Show Gist options
  • Select an option

  • Save Aareon/a0b83bc5ea9f8730c95c977fe97c19e4 to your computer and use it in GitHub Desktop.

Select an option

Save Aareon/a0b83bc5ea9f8730c95c977fe97c19e4 to your computer and use it in GitHub Desktop.
from PIL import Image
from colormath.color_objects import sRGBColor, LabColor
from colormath.color_conversions import convert_color
from colormath.color_diff import delta_e_cie2000
import numpy as np
import re
def rgb2hex(red, green, blue):
"""Return color as #rrggbb for the given color values."""
return '#%02x%02x%02x' % (red, green, blue)
def hex2rgb(value):
"""Return (red, green, blue) for the color given as #rrggbb."""
value = value.lstrip('#')
lv = len(value)
return tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3))
class Place:
def __init__(self):
self.place_colors_list = ["#FFFFFF", "#E4E4E4", "#888888",
"#222222", "#FFA7D1", "#E50000",
"#E59500", "#A06A42", "#E5D900",
"#94E044", "#02BE01", "#00D3DD",
"#0083C7", "#0000EA", "#CF6EE4",
"#820080", "#00FFFFFF"]
self.place_colors_names = ['WHITE', 'LIGHT GREY', 'GREY', 'BLACK', 'PINK', 'RED',
'ORANGE', 'BROWN', 'YELLOW', 'LIGHT GREEN', 'GREEN',
'CYAN', 'LIGHT BLUE', 'BLUE', 'VIOLET', 'PURPLE', 'TRANSPARENT']
def place_colors(self):
"""Requires: List containing hex values (palette)
Returns: List containing palette converted to LabColors"""
self.place_colors_lab = []
for color_to_convert in self.place_colors_list:
self.place_colors_lab.append(convert_color(sRGBColor(*hex2rgb(color_to_convert)), LabColor))
return self.place_colors_lab
def get_unique_colors(self, image):
"""Requires: Image
Returns: List of unique colors in image and numpy array for image"""
img = image
#x = (img.getdata()/img.size[1])/img.size[0]
img_data = np.array(img.getdata())
x = int(img_data.size/img.size[1]/img.size[0])
img_data = img_data.reshape(img.size[1], img.size[0], x)
unique_colors = []
for i in range(img.size[0]):
for j in range(img.size[1]):
try:
r, g, b,_ = img.getpixel((i, j))
except:
r, g, b = img.getpixel((i, j))
color_hex = rgb2hex(r,g,b)
if color_hex not in unique_colors:
unique_colors.append(color_hex)
print(len(unique_colors))
return unique_colors, img_data
def translate_colors(self, unique_colors):
"""Requires: List of unique colors in image
Returns: List of image colors translated to their closest relative
in the given palette"""
place_colors_lab = self.place_colors()
translated_colors = {}
number_completed_colors = 0
for color1 in unique_colors:
print(number_completed_colors)
color1_code = color1
deltas = []
color1 = convert_color(sRGBColor(*hex2rgb(color1)), LabColor)
for color2 in place_colors_lab:
deltas.append(delta_e_cie2000(color1, color2))
color1_health = min(deltas)
color1_closest = self.place_colors_names[deltas.index(color1_health)]
translated_colors[color1_code] = self.place_colors_list[self.place_colors_names.index(color1_closest)]
number_completed_colors += 1
return translated_colors
def placify_image(self, img, dict):
pixels = img.convert('RGBA').load()
width, height = img.size
for x in range(width):
for y in range(height):
r, g, b, a = pixels[x, y]
color = dict.get(rgb2hex(r, g, b))
if color != '#00FFFFFF"':
img.putpixel((x, y), hex2rgb(color))
else:
img.putpixel((x, y), (255, 255, 255, 0))
img.save('placed_images/'+input('Filename w/ extension: '))
img.save('doomguy-place.png')
def pixelate(self, image, divide=0):
"""Requires: Image
Returns: Pixelated image"""
img = Image.open(image) # The input image
width, height = img.size
if divide in [0,1]:
i = int(width)
j = int(height)
else:
i = int(width/divide)
j = int(height/divide)
print(width,height)
out = img.resize((i, j), resample=Image.LANCZOS) # Resize the image
out = out.resize((i, j), resample=Image.NEAREST)
out.save('pixelated.png')
"""Save the pixelated image"""
return out
if __name__ == '__main__':
print("Pixelating image...")
place = Place()
image = place.pixelate(input('Image filename w/ extension: '), divide=int(input('Divide by (int): ')))
print("Done... Getting unique colors...")
unique, image_dict = place.get_unique_colors(image)
print(unique)
print("Done... translating colors...")
translated_colors = place.translate_colors(unique)
print("Done... placifying image...")
place.placify_image(image, translated_colors)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment