Skip to content

Instantly share code, notes, and snippets.

@Kxrr
Last active November 7, 2016 11:56
Show Gist options
  • Save Kxrr/797688110cbdabb7f40a101cbcac7ef9 to your computer and use it in GitHub Desktop.
Save Kxrr/797688110cbdabb7f40a101cbcac7ef9 to your computer and use it in GitHub Desktop.
Image to Ascii
# -*- coding: utf-8 -*-
from PIL import Image
CHARS = list("""MNHQ$OC?7>!:-;. """)
CHARS_N = len(CHARS)
WIDTH = 40
HEIGHT = 40
def rgb2char(r, g, b, alpha=256):
if alpha == 0:
return ' '
gray = float(0.30 * r + 0.59 * g + 0.11 * b)
index = int(round(gray / 256 * (CHARS_N - 1)))
return CHARS[index]
def get_image(path):
im = Image.open(path)
im = im.resize((HEIGHT, WIDTH), Image.NEAREST)
return im
def image2text(im):
text = []
for i in range(HEIGHT):
for j in range(WIDTH):
text.append(rgb2char(*im.getpixel((j, i))))
text.append('\n')
return ''.join(text)
def convert(path):
image = get_image(path)
print(image2text(image))
if __name__ == '__main__':
convert('/Users/kxrr/Desktop/pinbot-logo.png')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment