Python 图片转字符画 学习笔记

时间:2023-03-08 18:28:01
Python 图片转字符画 学习笔记

Python 图片转字符画 学习笔记

标签(空格分隔): Python


声明:此文章和所有代码是学习笔记,非原创,原文教程地址:https://www.shiyanlou.com/courses/370/labs/1191/document

实验楼我感觉挺好的,但为了保存自己的代码,我是在自己本地电脑敲的代码,并且改造了一下。

这个教程是说如何把一个图片转化为字符画。

Python 图片转字符画 学习笔记
Python 图片转字符画 学习笔记

可以直接运行的代码如下:

from PIL import Image

IMG = "ascii_dora.png"
WIDTH = 80
HEIGHT = 80 ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ") def get_char(r, g, b, alpha=256):
if alpha == 0:
return ' '
length = len(ascii_char)
gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b) unit = (256.0 + 1) / length
return ascii_char[int(gray / unit)] im = Image.open(IMG)
im = im.resize((WIDTH, HEIGHT), Image.NEAREST) txt = "" for i in range(HEIGHT):
for j in range(WIDTH):
txt += get_char(*im.getpixel((j, i)))
txt += '\n' with open("output.txt", 'w') as f:
f.write(txt)

真简短。