将PIL图像转换为numpy数组有时不起作用

时间:2016-02-06 13:33:44

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

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

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是同一个对象: enter image description here

这很奇怪,因为此代码应将图像转换为numpy数组,如以下控制台会话所示: enter image description here

我无法理解这一点!为什么相同的代码行有时会起作用,有时也不会?

更新 似乎转换整个图像是有效的,但转换作物并不是这样: enter image description here enter image description here

我的完整代码是:

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

我用于测试的图像是: python logo 600*600

1 个答案:

答案 0 :(得分:1)

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