Skip to content

Instantly share code, notes, and snippets.

@WangYihang
Last active February 19, 2020 15:10
Show Gist options
  • Save WangYihang/42019c12a132c64e5410d1e563596694 to your computer and use it in GitHub Desktop.
Save WangYihang/42019c12a132c64e5410d1e563596694 to your computer and use it in GitHub Desktop.
from PIL import Image
'''
Black (0,0,0,1) (0,0,0) #000000
White (0,0,0,0) (255,255,255) #FFFFFF
Red (0,1,1,0) (255,0,0) #FF0000
Green (1,0,1,0) (0,255,0) #00FF00
Blue (1,1,0,0) (0,0,255) #0000FF
Yellow (0,0,1,0) (255,255,0) #FFFF00
Cyan (1,0,0,0) (0,255,255) #00FFFF
Magenta (0,1,0,0) (255,0,255) #FF00FF
'''
palette = [
(0, 0, 0),
(0, 0, 255),
(0, 255, 0),
(0, 255, 255),
(255, 0, 0),
(255, 0, 255),
(255, 255, 0),
(255, 255, 255),
]
def euclidDistance(p0, p1):
deltaR = p1[0] - p0[0]
deltaG = p1[1] - p0[1]
deltaB = p1[2] - p0[2]
return (deltaR ** 2 + deltaG ** 2 + deltaB ** 2) ** 0.5
def nearest(pixel, palette):
nearest_distance = (255 ** 2 + 255 ** 2 + 255 ** 2) ** 0.5
for i in range(len(palette)):
color = palette[i]
distance = euclidDistance(color, pixel)
if distance < nearest_distance:
nearest_distance = distance
nearest_distance_index = i
return palette[nearest_distance_index]
def traverse(image):
width = image.size[0]
height = image.size[1]
for x in range(width):
for y in range(height):
pixel = image.getpixel((x, y))
image.putpixel((x, y), nearest(pixel, palette))
image = Image.open("./lena.png")
target = image.copy()
traverse(target)
target.show()
target.save("./target.png")
@WangYihang
Copy link
Author

WangYihang commented Feb 19, 2020

Original Image

lena

Processed Image

target

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment