首页 > 技术文章 > 使用PIL将图片转成字符

mliu222 2019-11-17 23:28 原文

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

import numpy as np
from PIL import Image

if __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)

推荐阅读