使用PIL将图片转成字符

注意:转化成txt后,txt的字体使用“宋体”,不能使用“微软雅黑”,不然图像会变形字体

import numpy as npfrom PIL import Imageif __name__ == '__main__':    image_file = 'huarun3.png'    height = 100    img = Image.open(image_file)    img_width, image_height = img.size    print('img_width:', img_width)    print('image_height:', image_height)    width = int(height / image_height * img_width * 2)    img = img.resize((width, height), Image.ANTIALIAS)    print(img)    img_l = img.convert('L')    pixels = np.array(img_l)    print(img_l)    chars = 'MNHQ$OC?7>!:-;. '    step = 256 // len(chars)    result = ''    for i in range(height):        for j in range(width):            result += chars[pixels[i][j] // step]        result += '\n'    with open(image_file + '.txt', mode='w') as f:        f.write(result)
相关文章
相关标签/搜索