【问题标题】:convert PIL Image to numpy array sometimes don't work将 PIL Image 转换为 numpy 数组有时不起作用
【发布时间】:2016-02-06 13:33:44
【问题描述】:

我有这段代码可以打开图像并将其转换为灰度:

with Image.open(file_path).convert(mode='L') as image:
    ...
    block = image.crop((start_x, start_y, end_x, end_y))
    art[row] += tslt_block(block)

其中tslt_block()定义如下:

def tslt_block(img):
    char_table = "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. "
 -> a = np.array(img)
    gray_scale = a.mean()
    return char_table[int(gray_scale / 255 * (len(char_table) - 1))]

问题是,箭头标记的行(a = np.array(img))似乎没有效果!执行此行后,aimg 是同一对象:

这很奇怪,因为这段代码应该将图像转换为 numpy 数组,如下面的控制台会话所示:

我无法理解!为什么同一行代码有时有效,有时无效?

更新: 似乎转换整个图像有效,但转换裁剪没有:

我的完整代码是:

from PIL import Image
import numpy as np
import math, os

scale = 0.43


def tslt_block(img):
    char_table = "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. "
    a = np.array(img)
    gray_scale = a.mean()
    return char_table[int(gray_scale / 255 * (len(char_table) - 1))]


def main():
    file_path = input('input full file path: ')
    base_name, *_ = os.path.splitext(file_path)
    output_file_path = base_name + '.txt'
    columns = int(input('input number of columns: '))

    with Image.open(file_path).convert(mode='L') as image:
        width, height = image.size
        block_width = width / columns
        block_height = block_width / scale
        rows = math.ceil(height / block_height)
        art = []
        for row in range(rows):
            art.append('')
            for column in range(columns):
                start_x, start_y = column * block_width, row * block_height
                end_x = int(start_x + block_width if start_x + block_width < width else width)
                end_y = int(start_y + block_height if start_y + block_height < height else height)
                block = image.crop((start_x, start_y, end_x, end_y))
                art[row] += tslt_block(block)

    with open(output_file_path, 'w') as output_file:
        output_file.write('\n'.join(art))
        print('output written to {}'.format(output_file_path))


if __name__ == '__main__':
    main()

我用于测试的图像是:

【问题讨论】:

  • 你有可以重现这个问题的图片吗?
  • @Suever 是的。我已经更新了我的帖子并上传了图片。

标签: python arrays python-3.x numpy python-imaging-library


【解决方案1】:

好的,我已经解决了我自己的问题。似乎如果 start_x 和 start_y 是float,那么将裁剪后的图像更改为 numpy 数组将不起作用。如果我将它们转换为int,它就可以工作。但我仍然想知道为什么。 Pillow 或 numpy 有 bug 吗?

【讨论】:

  • 错误在您的代码中。 block_width = width / columnsblock_width 设置为浮点数。
  • @Dietrich Epp 如果我使用浮点数作为坐标,为什么不能将裁剪的图像转换为 numpy 数组?当我裁剪图像时,没有例外。
  • 在numpy中使用浮点数作为坐标没有任何意义。例如,a[2.5] 完全没有意义。它甚至应该是什么意思?为什么他们会有a[2.0] 的特殊情况?
猜你喜欢
  • 1970-01-01
  • 2017-06-25
  • 2017-05-10
  • 1970-01-01
  • 2010-09-27
  • 1970-01-01
  • 2020-02-17
  • 2011-02-15
  • 1970-01-01
相关资源
最近更新 更多