Skip to content

Instantly share code, notes, and snippets.

@lambdafu
Created December 9, 2017 19:06
Show Gist options
  • Save lambdafu/e5aafeaaf798f4bdceff8304c1056272 to your computer and use it in GitHub Desktop.
Save lambdafu/e5aafeaaf798f4bdceff8304c1056272 to your computer and use it in GitHub Desktop.
Convert an image to Unicode block graphic
# -*- 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()
@social-anthrax
Copy link

social-anthrax commented Mar 29, 2021

Sorry to necro this gist.
When running in Python 3.8.5, Line 18 will throw a Type error

resize return self._new(self.im.resize(size, resample, box))
TypeError: integer argument expected, got float

This can be fixed by casting the result of hsize/2 to int on line 18 as follows.

img = img.resize((WIDTH, (int) (hsize/2)), Image.ANTIALIAS)

Hopefully, that helps anyone else who finds themselves here.

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