# coding: utf-8
import numpy as np
from PIL import Image # pillow
if __name__ == '__main__':
image_file = '/Users/myhlb/Pictures/noi.jpg'
height = 100
img = Image.open(image_file)
img_width, img_height = img.size
#
width = 2 * height * img_width // img_height # 假定字符的高度是宽度的2倍
'''
由于采样不充分重建后造成的信息失真,就叫走样;用于减少或消除这种效果的技术,就称为反走样
'''
img = img.resize((width, height), Image.ANTIALIAS) # Image.ANTIALIAS 反走样
'''
convert()函数:
模式”1” 为二值图像,非黑即白
模式“L” 为灰色图像
'''
pixels = np.array((img.convert('L'))) # 灰度图:img.convert('L')
print(pixels.shape)
print(pixels) # pixels为若干行若干列的两维数组
chars = "MNHQ$OC?7>!:-;. " # 控制图像颜色深浅
N = len(chars)
step = 256 // N
print(N)
result = ''
for i in range(height):
for j in range(width):
result += chars[pixels[i][j] // step]
result += '\n'
with open('/Users/myhlb/Documents/text.txt', mode='w') as f:
f.write(result)
图片转成字符图画-学习笔记
最新推荐文章于 2023-08-16 17:14:11 发布