python【图片转字符画】,图片灰度值处理

老规矩,先上效果图
python【图片转字符画】,图片灰度值处理_第1张图片

python【图片转字符画】,图片灰度值处理_第2张图片
理论很简单,就是对图片操作,这里需要用到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,字符画,灰度值,pil)