把图片不同的颜色用不同的字符表示
from PIL import Image
def getchar(r, g, b):
txt = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'.")
gray = 0.2126 * r + 0.7152 * g + 0.0722 * b
bili = 256 / len(txt)
index = int(gray / bili)
return txt[index]
image = Image.open("mi.jpeg")#导入一张图片
width = 100
height = 50
image = image.resize((width, height), Image.NEAREST)
txt = ""
for y in range(height):
for x in range(width):
pix = image.getpixel((x, y))
txt += getchar(*pix)
txt += "\n"
with open("wy1.txt", "w", encoding="utf-8") as file:#生成名叫wy1的txt文件,里面就是字符画
file.write(txt)
file.close()
名为mi的图片
![](https://img-blog.csdnimg.cn/aee544cf360c4d829b2ff4d5cbae97dd.jpeg)