手把手教你如何將圖片轉換成字符畫


步驟:

1.將圖片轉換為黑白圖

2.遍歷所有像素點,建立像素點和字符的映射,保存為一個字符串

3.將字符串輸出到文件里面就可以了(*^▽^*)

示例:

(emmmmm這里沒有完整截下來)

 1 from PIL import Image
 2 def getText(img):
 3     img = img.convert("L")  #轉為灰度圖片
 4     charlist = ''
 5     for h in range(0,img.size[1]):
 6         for w in range(0,img.size[0]):
 7             gray = img.getpixel((w,h))  #返回像素值,介於0-255之間256個
 8             pos = gray/256
 9             charlist = charlist + codelist[int((count-1)*pos)]  #這里count-1是因為字符串索引是從0開始
10         charlist = charlist+'\r\n'  #不同系統對應的換行符不一樣\n-windows \r-Linux
11     return charlist
12 
13 def getImage():
14     #取得圖像
15     file = open(u'1.jpg', 'rb')
16     img = Image.open(file)
17     return img
18 
19 def trantxt():
20     #輸出到文本中去
21     outfile = open('tmp.txt', 'w')
22     outfile.write(getText(img))
23     outfile.close()
24 
25 if __name__ == '__main__':
26     img = getImage()
27     width, height = img.size[0],img.size[1] #0-width,1-height
28     codelist = """qwertyuiop[]asdfghjkl;'zxcvbnm,./`~!@#$%^&<()*+{}:"?> |""" 
29     count = len(codelist)
30     scale = width / height  #寬度與高度的比例,為了維護圖像比例不要失真
31     img = img.resize((int(width*0.1), int(width*0.1/scale) ))   #這里的0.1可以改成你喜歡的比例
32     trantxt()

ps. 如果你用記事本打開輸出文件,記得關閉自動換行

如需轉載請注明出處喲

喜歡就支持一下唄~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM