gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 16:58:25 25 4
gpt4 key购买 nike

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

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 数组,如以下控制台 session 所示: 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

最佳答案

好的,我已经解决了我自己的问题。似乎如果 start_x 和 start_y 是浮点型,那么将裁剪后的图像更改为 numpy 数组将不起作用。如果我将它们转换为 int,它就可以工作。但我还是想知道为什么。 Pillow 或 numpy 是否存在错误?

关于python - 将 PIL 图像转换为 numpy 数组有时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35241626/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com