Python 50行代碼實現圖片轉字符畫

最近在尋找python練手的項目,加深語法的熟練程度
知乎一個回答給出的項目很合適,以下為該項目的學習筆記。

項目鏈接:

https://www.shiyanlou.com/courses/370/labs/1191/document

運行效果:
原圖
字符畫
完整代碼:

python
from PIL import Image
import argparse

字符畫所用的字符集

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

def getChar(r,g,b,alpha=256):
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)]

parser = argparse.ArgumentParser()

parser.add_argument('file')
parser.add_argument('-o','--output')
parser.add_argument('--width', type = int, default = 80)
parser.add_argument('--height', type = int, default = 80)

args = parser.parse_args()

IMG = args.file
WIDTH = args.width
HEIGHT = args.height
OUTPUT = args.output

if name == 'main':

im = Image.open(IMG)
im = im.resize((WIDTH,HEIGHT),Image.NEAREST)

txt=""

for i in range(HEIGHT):
    for j in range(WIDTH):
        txt += getChar(*im.getpixel((j,i)))
    txt += '\n'

print(txt)

if OUTPUT:
    with open(OUTPUT,'w') as f:
        f.write(txt)
else:
    with open('output.txt','w') as f:
        f.write(txt)

#####學習筆記:
1. <code>argparse</code>以前沒用過,傳遞參數似乎比<code>sys.argv</code>強大許多
以前我只會用 <code>sys.argv[1] </code>這種方式來給腳本傳遞參數并做相應判斷

1. 處理圖像的<code>Pillow</code>聞名已久,以后做圖像處理時可以再重點了解
1. RGB值轉字符的函數 <code>getChar</code>,開始很費解,不明白什么意思,自己逐句運行了一次才懂。
```python```
def get_char(r,g,b,alpha = 256):
        if alpha == 0: 
                return ' ' 

        #先得出字符組的長度
        length = len(ascii_char) 
       
        #計算對像素點的灰度
        gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)   
       
        #計算出灰度與字符串長度的對應比
        unit = (256.0 + 1)/length

        #gray/unit 的結果決定了使用字符組中的哪一個字符
        return ascii_char[int(gray/unit)]
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容