Python将图片转化ASCII

用Python将图片转化ASCII

思路

将彩图转化为灰度模式(去掉颜色),再更具每个像素的灰度值找到不同复杂度的ASCII字符一一映射,从而转换为ASCII字符图像

环境(我的环境)

1. python3.7
2. Pillow库
注意:Pillow库与PIL库不可存在于同一环境
3. 图片

iyxRP0.md.png

实现步骤

1. 导入Pillow库

from PIL import Image

2. 读取图片并将其转换为灰度模式(去色)
1
2
3
img = Image.open("tomtony.png")
img_gray = img.convert("L")
img_gray.show()

iyx5MF.md.jpg

3. 重置图片大小

img_gray = img_gray.resize((int(img_gray[0] * 0.5), int(img_gray[1] * 0.5)))
0.5为缩放大小可随意修改

4. 根据灰度值转化为ASCII

灰度模式的图像它每个像素有一个灰度值,这个值的范围是 0 ~ 255,它的值越小说明它越黑(0是纯黑色,255是纯白色)

获取灰度值

img_gray.getpixel(100, 100)
图像在100*100这个像素的灰度值

根据灰度值将图像转化为asci
1
2
3
4
5
6
7
asciis = "@%#*+=-:. "
texts = ''
for row in range(height):
for col in range(width):
gray = img_gray.getpixel((col, row))
texts += asciis[int(gray / 255 * 9)] # 根据灰度值选择不同复杂度的 ASCII 字符
texts += '\n'
5. 最后保存为文件
1
2
with open("ascii.txt", "w") as f:
f.write(texts)

iyz3WV.jpg

最终代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
from PIL import Image

def get_pic_info(pic, zoom_pic):
img = Image.open(pic)
img_gray = img.convert('L')
width, height = img_gray.size
img_gray = img_gray.resize((int(width * zoom_pic), int((height * zoom_pic) * 0.5)))
size = img_gray.size
return size, img_gray

def get_ascils(pic_info):
width = pic_info[0][0]
height = pic_info[0][1]
img_gray = pic_info[1]
ascils = '@%#*+=_. '
texts = ""
for row in range(height):
for col in range(width):
gray = img_gray.getpixel((col, row))
texts += ascils[int(gray / 255 * 8)]
texts += '\n'
return texts

def save_ascil(pic_to_ascils, pic):
name = ''.join(pic.split('.')[:-1]) + str('.txt')
with open(name, 'w') as file:
file.write(pic_to_ascils)

def main():
pic = input('请放入图片:')
zoom_pic = float(input('请输入缩放比例(eg:0.1):'))
pic_info = get_pic_info(pic, zoom_pic)
pic_to_ascils = get_ascils(pic_info)
save_ascil(pic_to_ascils, pic)

if __name__ == '__main__':
main()

此篇blog是学习了小甲鱼的极客Python之效率革命的将你的女神变成字符画之后写的学习笔记