[英]convert PIL Image to numpy array sometimes don't work
我有這段代碼來打開圖像並將其轉換為灰度:
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)
)似乎無效! 執行此行后, a
是與img
相同的對象:
這很奇怪,因為此代碼會將圖像轉換為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()
好,我已經解決了自己的問題。 似乎如果start_x和start_y為float
,則將裁剪后的圖像更改為numpy數組將不起作用。 如果我將它們轉換為int
,它將起作用。 但是我仍然想知道為什么。 枕頭或numpy中是否有錯誤?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.