python學習---50行代碼實現圖片轉字元畫1

來源:互聯網
上載者:User

標籤:www   建立   項目   el函數   unit   lan   col   計算   python   

轉自:78447714

項目連結: https://www.shiyanlou.com/courses/370/labs/1191/document

 

 

from PIL import Image   #從PIL模組中引入Image這個類
import argparse   #引入argparse這個模組(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.file
WIDTH = args.width
HEIGHT = args.height
OUTPUT = args.output

#定義一個ascii的列表,讓圖片上的灰階與字元相對應

ascii_char = list("[email protected]%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!1I;:,\"^`‘.")

#將256灰階映射到70個字元上

def get_char(r,g,b,alpha = 256):   #這個調用跟im.getpixel函數有關,這個函數是根據圖片的橫縱座標,把圖片解析成

                  #r,g,b,alpha(灰階)

  if alpha == 0:  #如果灰階是0,則說明這裡沒有圖片
  return ‘ ‘
  length = len(ascii_char)  #計算這些字元的長度
  gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)  #把這些圖片的RGB值轉換成灰階值
  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)))  #把圖片按照橫縱座標解析成RGBAlpha這幾個參數,然後調用get_char

                        #函數,把對應的圖片轉換成灰階值,把對應值的字元存入txt中
      txt += ‘\n‘
    print(txt)  #在介面列印txt檔案

  if OUTPUT:
    with open(OUTPUT,‘w‘) as f:  #檔案輸出
    f.write(txt)
  else:
    with open("xx.txt",‘w‘) as f:  #檔案輸出
    f.write(txt)

python學習---50行代碼實現圖片轉字元畫1

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.