python 圖片轉字元畫

來源:互聯網
上載者:User

標籤:txt   div   bubuko   輸入參數   pen   擷取   python   add   port   

整代碼:

將以下代碼儲存為py檔案

from PIL import Imageimport argparse#命令列輸入參數處理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.fileWIDTH = args.widthHEIGHT = args.heightOUTPUT = args.outputascii_char = list("[email protected]%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`‘. ")# 將256灰階映射到70個字元上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    return ascii_char[int(gray/unit)]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 += get_char(*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)

把要轉成字元畫的圖片置於該檔案的同級目錄下

 

然後cmd開啟命令列視窗

 

python 圖片轉字元畫

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.