Created
December 9, 2017 19:06
-
-
Save lambdafu/e5aafeaaf798f4bdceff8304c1056272 to your computer and use it in GitHub Desktop.
Convert an image to Unicode block graphic
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from __future__ import print_function | |
import numpy as np | |
from PIL import Image | |
import matplotlib.pyplot as plt | |
import sys | |
THRESHOLD_VALUE = 128 | |
WIDTH = 120 | |
img = Image.open(sys.argv[1]) | |
img = img.convert("1") | |
wpercent = (WIDTH/float(img.size[0])) | |
hsize = int((float(img.size[1])*float(wpercent))) | |
img = img.resize((WIDTH, hsize/2), Image.ANTIALIAS) | |
img.save("out.png") | |
w, h = img.size | |
data = np.asarray(img).copy() | |
data.resize(h, w) | |
# left top, right top, left bottom, right bottom | |
chrs = np.empty((2, 2, 2, 2), dtype=object) | |
chrs[0][0][0][0] = " " | |
chrs[0][0][0][1] = "▗" | |
chrs[0][0][1][0] = "▖" | |
chrs[0][0][1][1] = "▄" | |
chrs[0][1][0][0] = "▝" | |
chrs[0][1][0][1] = "▐" | |
chrs[0][1][1][0] = "▞" | |
chrs[0][1][1][1] = "▟" | |
chrs[1][0][0][0] = "▘" | |
chrs[1][0][0][1] = "▚" | |
chrs[1][0][1][0] = "▌" | |
chrs[1][0][1][1] = "▙" | |
chrs[1][1][0][0] = "▀" | |
chrs[1][1][0][1] = "▜" | |
chrs[1][1][1][0] = "▛" | |
chrs[1][1][1][1] = "█" | |
for y in range(0, h-1, 2): | |
for x in range(0, w-1, 2): | |
tl = 1 if data[y][x] else 0 | |
tr = 1 if (data[y][x+1] if x < w else False) else 0 | |
bl = 1 if (data[y+1][x] if y < h else False) else 0 | |
br = 1 if (data[y+1][x+1] if x < w and y < h else False) else 0 | |
#print tl, tr, bl, br | |
print (chrs[tl][tr][bl][br], end="") | |
print() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sorry to necro this gist.
When running in Python 3.8.5, Line 18 will throw a Type error
This can be fixed by casting the result of
hsize/2
to int on line 18 as follows.Hopefully, that helps anyone else who finds themselves here.