python - convert PIL Image to numpy array sometimes don't work -
i have block of code open image , convert gray scale:
with image.open(file_path).convert(mode='l') image: ... block = image.crop((start_x, start_y, end_x, end_y)) art[row] += tslt_block(block) where tslt_block() defined follows:
def tslt_block(img): char_table = "$@b%8&wm#*oahkbdpqwmzo0qlcjuyxzcvunxrjft/\|()1{}[]?-_+~<>i!li;:,\"^`'. " -> = np.array(img) gray_scale = a.mean() return char_table[int(gray_scale / 255 * (len(char_table) - 1))] the problem is, line marked arrow(a = np.array(img)) seems have no effect! after line executed a same object img: 
this pretty weird since code should translate image numpy array, shown in following console session: 
i can't understand this! why same line of code works , doesn't?
update: seems converting whole image works, converting crop doesn't:

my complete code is:
from pil import image import numpy np import math, os scale = 0.43 def tslt_block(img): char_table = "$@b%8&wm#*oahkbdpqwmzo0qlcjuyxzcvunxrjft/\|()1{}[]?-_+~<>i!li;:,\"^`'. " = 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: ')) image.open(file_path).convert(mode='l') image: width, height = image.size block_width = width / columns block_height = block_width / scale rows = math.ceil(height / block_height) art = [] row in range(rows): art.append('') 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) open(output_file_path, 'w') output_file: output_file.write('\n'.join(art)) print('output written {}'.format(output_file_path)) if __name__ == '__main__': main()
ok, i've solved own problem. seems if start_x , start_y float, changing cropped image numpy array won't work. if convert them int, works. still wonder why. there bug in pillow or numpy?

Comments
Post a Comment