python【圖片轉字元畫】,圖片灰度值處理

2021-03-10 12:00:21

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

小夥伴有什麼問題可以和小編交流。這裡需要自行下載PIL包,如果不知道怎麼下載的話,也可以問我拿。

在這裡插入圖片描述