使用PIL在终端中显示图像(png)

sup*_*oon 5 python python-imaging-library python-3.x

环境:

Python 3.7.2 Mac OS 10.14.3

我试图找到一种在终端应用程序中显示图像(jpg / png)的方法。

我在这里找到了jpg图片的可行解决方案:

使用Python在Linux Terminal中显示图像

使用以下代码:

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])
Run Code Online (Sandbox Code Playgroud)

问题是,当我尝试将此代码用于png文件时,出现错误:

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.
Run Code Online (Sandbox Code Playgroud)

似乎在处理jpg文件时pix是元组,而在处理png文件时pix是int值。

任何建议将不胜感激,谢谢:)

Mar*_*ell 2

您的图像可能是灰度的或调色板的。不管怎样,只有 1 个通道,而不是 3 个。所以改变这一行

img = Image.open(img_path)
Run Code Online (Sandbox Code Playgroud)

img = Image.open(img_path).convert('RGB')
Run Code Online (Sandbox Code Playgroud)

这样您就可以获得您期望的 3 个频道,并且一切都运行良好。


我注意到您的调整大小代码试图在调整大小的图像中保持相同的纵横比,这非常值得称赞,但是......终端上的像素实际上并不是方形的!如果您近距离观察光标,它的高度大约是宽度的 2 倍,因此我更改了调整大小代码行以实现此目的:

w = int((img.width / img.height) * h) * 2
Run Code Online (Sandbox Code Playgroud)

关键词:PIL、Pillow、终端、控制台、ANSI、转义序列、图形、ASCII 艺术、图像、图像处理、Python