1. 安裝PIL庫或者Pillow
PIL(Python Imaging Library)是Python一個強大方便的圖像處理庫,名氣也比較大。不過只支持到Python 2.7。Pillow是PIL的一個派生分支,但如今已經發展成爲比PIL本身更具活力的圖像處理庫
命令行pip安裝:
pip install Pillow
在當前文件下快速打開控制檯方法:
shift + 鼠標右鍵
2.項目代碼:
from PIL import Image
# 調整轉換後圖片分辨率(手動調整)
WIDTH = 400
HEIGHT = 400
# 根據原圖灰度大小計算轉換後所用字符
def get_char(r, g, b, a=256):
if a == 0:
return " "
gray = int(0.2126*r + 0.7152*g + 0.0722*b)
unit = 257/len(char_list)
return char_list[int(gray/unit)]
# 圖片處理函數
def get_pic(path):
img = Image.open(path)
# 調整原圖大小
img = img.resize((WIDTH, HEIGHT), Image.NEAREST)
# 文字雲
text = ""
# 圖片像素遍歷
for y in range(HEIGHT):
for x in range(WIDTH):
pixel = img.getpixel((x, y))
text += get_char(*pixel)
text += '\n'
with open("out.txt", 'w') as out:
out.write(text)
pass
if __name__ == '__main__':
# 字符表
char_list = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")
get_pic("img.jpg")
pass
原圖:
轉換後: