1.設計思路
如何把以.png的圖片以不同字符把它形象的畫出來呢?
我們知道其實一張圖片是由很多不同像素點所組成的,每種像素點可以表示一種顏色。那麼如果我們用不同的字符來代替各種像素點,是不是就可以將圖片轉化爲字符畫了?沒錯就是要用這個原理
2.需做的準備
爲了實現我們本片博文所述的功能,不許得有一個叫做Pillow(PIL)的圖像處理庫
該庫的安裝方式如下
pip install pillow
我們今天所要使用的是該庫中的Image模塊.。其中會用到一個很重要的概念-灰度值(由圖形顏色的深淺來決定)
關於Image模塊的詳細用法請戳http://www.cnblogs.com/apexchu/p/4231041.html
3.代碼實現
#! /usr/bin/python
#coding:utf8
import argparse
from PIL import Image
def handle_command():
'命令行參數處理'
parser = argparse.ArgumentParser()
parser.add_argument('filename',help = '圖片的路徑')
parser.add_argument('-o','--output',help = '是否輸出文件')
parser.add_argument('--width',type = int,default = 80)
parser.add_argument('--heigth',type = int,default = 80)
#獲取命令行參數
return parser.parse_args()
args = handle_command()
class Ptrancefrom(object):
'實現將圖片轉化爲字符'
def __init__(self,img,width,heigth):
self.img = img
self.width = width
self.heigth = heigth
self.ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")
def get_char(self,r,b,g,alpha = 256):
'將256範圍的灰度值映射到70個字符上'
#灰度值爲0時對應字符爲空格
if alpha == 0:
return ' '
length = len(self.ascii_char)
#灰度值的計算公式
gray = int(0.2126 *r + 0.7152*g + 0.0722*b)
unit = (256.0 + 1)/length
return self.ascii_char[int(gray/unit)]
def print_picture(self):
'打印圖形'
#打開圖片
im = Image.open(self.img)
#設置圖片像素的大小
im = im.resize((self.width,self.heigth),Image.NEAREST)
txt = ""
for i in range(self.heigth):
for j in range(self.width):
txt += self.get_char(*im.getpixel((j,i)))
txt += '\n'
print txt
def write_to_file(self):
'將生成的字符圖片寫入到文件'
if args.output:
with open(args.output,'w') as f:
f.write(txt)
else:
with open('output.txt','w') as f:
f.write(txt)
pic = Ptrancefrom(args.filename,args.width,args.heigth)
pic.print_picture()
運行上述腳本
python prog3.py --width 45 --heigth 45 ascii_dora.png
選材的圖片原圖如下
效果圖如下