【发布时间】: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))似乎没有效果!执行此行后,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()
【问题讨论】:
-
你有可以重现这个问题的图片吗?
-
@Suever 是的。我已经更新了我的帖子并上传了图片。
标签: python arrays python-3.x numpy python-imaging-library