python创作字符画

老规矩,先上效果图
在这里插入图片描述

在这里插入图片描述
理论很简单,就是对图片操作,这里需要用到PIL的python包,里面有很好用的图像处理功能。

先打开图片,把图像调整大小。

img = Image.open(picPath)
img = img.resize((picW, picH))

然后读取灰度值,再把灰度值和字符对应起来就行。

from PIL import Image

lstChars = list("$@B%8&WM#*oahkbdpqwmZO0QLaCJUYXzczjhdhsdavunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'.") 

def oneChars(r, g, b, alpha = 256):
    global lstChars
    length = len(lstChars)
    gray = int(0.2126 * r + 0.7152 * g + 0.722 * b)
    index =length*gray
    return lstChars[index]

picPath = "C:\Users\Administrator\Desktop\\aaaaa\\aa.png"
picH = 40
picW =  80

img = Image.open(picPath)
img = img.resize((picW, picH))

txt = ""
for y in range(picH):
    for x in range(picW):
        txt += oneChars(img.getpixel((x, y)))
    txt += '\n'

print txt

python收徒,对python编程,有兴趣的同学可以关注公众号:诗一样的代码,找我一起讨论学习。

猜你喜欢

转载自juejin.im/post/7112691836849750047