Environment:
Python 3.7.2 Mac OS 10.14.3
I am try to find a way to show a image (jpg/png) in the terminal application.
And I found a working solution for jpg image here:
Display Images in Linux Terminal using Python
With the following code:
import numpy as np
from PIL import Image
def get_ansi_color_code(r, g, b):
if r == g and g == b:
if r < 8:
return 16
if r > 248:
return 231
return round(((r - 8) / 247) * 24) + 232
return 16 + (36 * round(r / 255 * 5)) + (6 * round(g / 255 * 5)) + round(b / 255 * 5)
def get_color(r, g, b):
return "\x1b[48;5;{}m \x1b[0m".format(int(get_ansi_color_code(r,g,b)))
def show_image(img_path):
try:
img = Image.open(img_path)
except FileNotFoundError:
exit('Image not found.')
h = 100
w = int((img.width / img.height) * h)
img = img.resize((w, h), Image.ANTIALIAS)
img_arr = np.asarray(img)
for x in range(0, h):
for y in range(0, w):
pix = img_arr[x][y]
print(get_color(pix[0], pix[1], pix[2]), sep='', end='')
print()
if __name__ == '__main__':
show_image(sys.argv[1])
The problem is when I try to use this code for a png file I get the error:
Traceback (most recent call last):
File "img-viewer.py", line 62, in <module>
show_image(sys.argv[1])
File "img-viewer.py", line 40, in show_image
print(get_color(pix[0], pix[1], pix[2]), sep='', end='')
IndexError: invalid index to scalar variable.
It seems like when processing a jpg file the pix
is a tuple while with a png file the pix
is a int value.
Any advice will be appreciated, thanks :)
Your image may be greyscale, or palettised. Either way there will only be 1 channel, not 3. So change this line
img = Image.open(img_path)
to
img = Image.open(img_path).convert('RGB')
so you get the 3 channels you expect and it all works nicely.
I noticed that your resizing code tries to keep the same aspect ratio in the resized image, which is all very laudable, but... the pixels on a Terminal are not actually square! If you look at the cursor up close, it is around 2x as tall as it is wide, so I changed the line of resizing code to allow for this:
w = int((img.width / img.height) * h) * 2
Keywords: PIL, Pillow, terminal, console, ANSI, escape sequences, graphics, ASCII art, image, image processing, Python
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With