Created
January 28, 2020 20:50
-
-
Save dov/1af4b90d3d5e8c3a27a7c9c9324abe5f to your computer and use it in GitHub Desktop.
This file contains 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
#!/usr/bin/python | |
# Cat a np array from a .npy file | |
import numpy as np | |
from PIL import Image | |
import sys | |
def die(msg): | |
msg += "\n" if msg[-1]!="\n" else "" | |
sys.stderr.write(msg) | |
argp = 1 | |
DoUni = False | |
DoBlock = True | |
while argp < len(sys.argv) and sys.argv[argp][0]=='-': | |
S_ = sys.argv[argp] | |
argp+= 1 | |
if S_=='-help': | |
print('pretty print a np array in a terminal\n' | |
'\n' | |
'Syntax:\n' | |
' npcat [--uni] arr\n' | |
'Options:\n' | |
' --uni Use unicode block characters' | |
) | |
exit(0) | |
if S_=='--uni': | |
DoUni= True | |
continue | |
if S_=='--circle': | |
DoUni = True | |
DoBlock= False | |
continue | |
die('Unknown option ' + S_) | |
if argp >= len(sys.argv): | |
die("Need name of bitmap!") | |
Filename = sys.argv[argp] | |
argp+= 1 | |
if Filename.endswith('.png'): | |
im = np.array(Image.open(Filename)) | |
if im.dtype == np.bool: | |
im = im.astype(np.uint8) | |
elif Filename.endswith('.npy'): | |
im = np.load(Filename) | |
else: | |
die('Unsupported extension!') | |
if DoUni or DoCompact: | |
if im.min() < 0 or im.max() > 1: | |
die('Can only do unicode or compact printing on binary images') | |
Chars = '█ ' if DoBlock else '⬤◯' | |
for row in im.tolist(): | |
print(''.join(Chars[v] for v in row)) | |
else: | |
print(im) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment