天天看點

Python圖轉字元畫

本文參考:

https://blog.csdn.net/qq_20464153/article/details/79777823

将一副圖以灰階值轉化成黑白字元畫

代碼如下:

# -*- coding:utf-8 -*-
from PIL import Image

IMG = r'F:\PythonFiles\PycharmFile\ex10CharacterGraph.jpg'  #檔案路徑

WIDTH = 80  #定義輸出畫面的寬度
HEIGHT = 45  #定義
ascii_char = list("[email protected]%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")  #所用字元清單

# 将256灰階映射到70個字元上
def get_char(r, g, b, alpha=256):  # alpha透明度
    if alpha == 0:
        return ' '
    length = len(ascii_char)
    gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)  # 計算灰階
    unit = (256.0 + 1) / length
    return ascii_char[int(gray / unit)]  # 不同的灰階對應着不同的字元

# 通過灰階來區分色塊
if __name__ == '__main__':  #__name__ == '__main__'表示以下程式隻要在本檔案運作時才執行;若該檔案被其他檔案import引用,以下程式則不執行
    im = Image.open(IMG)
    im = im.resize((WIDTH, HEIGHT), Image.NEAREST)
    txt = ""
    for i in range(HEIGHT):
        for j in range(WIDTH):
            txt += get_char(*im.getpixel((j, i)))
        txt += '\n'
    print(txt)  #輸出圖像

    # 将圖像寫入txt檔案
    with open("ex10CharacterGraph_Graph.txt", 'w') as f:
        f.write(txt)  

           

效果圖:

Python圖轉字元畫
Python圖轉字元畫