from sys import argv from PIL import Image table = {(255, 255, 255) : "A", (228, 228, 228) : "B", (136, 136, 136) : "C", (34, 34, 34) : "D", (255, 167, 209) : "E", (229, 0, 0) : "F", (229, 149, 0) : "G", (160, 106, 66) : "H", (229, 217, 0) : "I", (148, 224, 68) : "J", (2, 190, 1) : "K", (0, 211, 221) : "L", (0, 131, 199) : "M", (0, 0, 234) : "N", (207, 110, 228) : "O", (130, 0, 128) : "P", None : "Q"} def dist2(p,q): '''squared euclidian distance between two lists of same size''' s = 0 for i in range(len(p)): s += (p[i]-q[i])**2 return s def closest_color(c, color_list): m, cm = 3 * 255**2, None for color in color_list: if dist2(c, color) < m: m = dist2(c, color) cm = color return cm def convert_pixel(px, convert_table, color_list, threshold = 100): if px[-1] < threshold: return convert_table[None] return convert_table[closest_color(px[:-1], color_list)] def convert_img(I, convert_table): color_list = list(convert_table.keys())[:-1] return [ "".join([convert_pixel(px, convert_table, color_list) for px in line]) for line in I] def main(): path = argv[1] img = Image.open(path).convert('RGBA') width, height = img.size I = list(img.getdata()) I = [I[i * width:(i + 1) * width] for i in range(height)] converted = convert_img(I, table) f = open(path + '.txt', 'w') f.write(str(converted)) f.close() main()