用python 控制檯列印圖片示例
阿新 • • 發佈:2019-02-12
功能:利用 python 的 image模組和簡單用符號,再控制檯打印出圖片的圖片輪廓
PIL 安裝 pip install Pillow
步驟:
1、拿到圖片物件,並轉換圖片模式(‘’L‘’),L模式可以去到圖片的個畫素的灰度引數;
2、定義圖片縮放長度、替換字元的串(根據灰度值排序);
3、遍歷縮放後每一個點位置,並獲取該點位置的灰度值,根據灰度值替換為相應的替換字元;
4、列印在控制檯;
程式碼如下:
#-*- coding:utf-8 -*- from PIL import Image import sys import os def _main(): try: pic = os.path.abspath(sys.argv[1]) #獲取圖片路徑引數 except: print('指定圖片路徑') img = Image.open(pic) #獲取圖片物件 width = img.width #獲取圖片寬度 height = img.height #獲取圖片高度 gray_img = img.convert('L') #圖片轉換為'L'模式 模式“L”為灰色影象,它的每個畫素用8個bit表示,0表示黑,255表示白,其他數字表示不同的灰度 scale = width // 100 #圖片縮放100長度 char_lst = ' .:-=+*#%@' #要替換的字元 char_len = len(char_lst) #替換字元的長度 for y in range(0, height, scale): #根據縮放長度 遍歷高度 for x in range(0, width, scale): #根據縮放長度 遍歷寬度 choice =gray_img.getpixel((x, y)) * char_len // 255 #獲取每個點的灰度 根據不同的灰度填寫相應的 替換字元 if choice==char_len: choice=char_len-1 sys.stdout.write(char_lst[choice]) #寫入控制檯 sys.stdout.write('\n') sys.stdout.flush() if __name__ == '__main__': _main()
使用:
將上面程式碼寫入到picture.py中,執行命令:python picture.py ImgURL
效果如下: