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

标签 python python-3.x python-imaging-library

环境:

python 3.7.2 Mac 操作系统 10.14.3

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

我在这里找到了 jpg 图像的工作解决方案:

Display Images in Linux Terminal using Python

使用以下代码:

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])

问题是当我尝试将此代码用于 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.

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

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

最佳答案

您的图像可能是灰度图像或调色板。无论哪种方式,都只有 1 个 channel ,而不是 3 个。所以更改此行

img = Image.open(img_path)

img = Image.open(img_path).convert('RGB')

因此您获得了预期的 3 个 channel ,并且一切正常。


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

w = int((img.width / img.height) * h) * 2

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

关于python - 使用 PIL 在终端中显示图像 (png),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54777720/

相关文章:

python - 我可以使用 PIL 以全屏模式显示图像吗?

python - Pandas 数据帧 : convert columns into rows of a single column

python - 为什么我在执行 GroupBy 后会丢失数据?

linux - 如何在 home 'not root' 安装 python3.4?确保点失败

python - 优化算法以找到渐进学习曲线

python - 导入错误 : The _imagingft C module is not installed in alpine-docker

python PIL : Create indexed color image with transparent background

python - 如何从 Pandas 日期时间列中提取组件并分配它们

python - 是否可以使用 boto 从 Google App Engine 中的 S3 读取文件?

python - 使用 SWIG 将 C++ 对象指针传递给 Python,而不是再次传回 C++