Python实战1- 图片转字符画
Python實戰系列用于記錄實戰項目中的思路,代碼實現,出現的問題與解決方案
本文為第1篇–圖片轉字符畫
參考教程:https://www.cnblogs.com/MartinLwx/p/9143844.html
一、步驟
分析:字符畫原理是將圖片的灰度值與個人設定的字符集之間建立映射關系,不同區間的灰度值對應不同的字符,之后將圖片每一個像素對應的字符打印出來,即可獲得字符畫
將原圖片轉化為灰度圖片
方案一:利用灰度公式將像素的 RGB 值映射到灰度值
gray = 0.2126 * r + 0.7152 * g + 0.0722 * b
方案二:利用PIL庫所帶的convert(“L”)函數轉化圖片
將圖片的灰度值與個人設定的字符集之間建立映射關系
可以自己設定,也可以找網上教程里給出的,下面將給出兩種參考方案
方案一:
方案二:
ascii_char = list("qwertyuiop[]asdfghjkl;'zxcvbnm,./`~!@#$%^&<()*+{}:"?> |")經測試,方案二生成的圖片真實度更高
將字符串保存到txt文件
二、代碼實現
注:IDE為Spyder,Python版本為3.6,推薦使用Anaconda,自帶Pillow庫。否則要提前安裝好pillow。
pillow庫安裝教程:
代碼實現如下:
# -*- coding: utf-8 -*- """ Created on Fri Sep 28 23:23:44 2018@author: PastoralDog """ from PIL import Imageclass ASCIIart(object):def __init__(self,file):self.file=fileself.codelist = """qwertyuiop[]asdfghjkl;'zxcvbnm,./`~!@#$%^&<()*+{}:"?> |"""self.img=Image.open(file)self.count=len(self.codelist)def to_ASCII(self):img = self.img.convert("L")asciilist = ''for h in range(0,img.size[1]):for w in range(0,img.size[0]):gray = img.getpixel((w,h))pos = gray/256#asciilist = asciilist + self.codelist[int((self.count-1)*pos)]asciilist = asciilist + self.codelist[int((self.count-1)*pos)]+" "+self.codelist[int((self.count-1)*pos)]asciilist = asciilist+"\n"return asciilistdef to_txt(self):outfile = open('ASCIIart.txt', 'w')outfile.write(self.to_ASCII())outfile.close()def _resize(self,rate):width = self.img.size[0]height = self.img.size[1]scale = width / heightself.img = self.img.resize((int(width*rate), int(width*rate/scale) ))if __name__ == '__main__':file="test.jpg"img=ASCIIart(file)img.to_txt()三、出現的問題及解決方案
圖像失真嚴重
采用方案一的編碼生成的字符畫效果不是很好,改用方案二后得到解決
圖像左右過于窄
我們以下圖為例
第二張核心代碼:
第三張核心代碼:
asciilist = asciilist + self.codelist[int((self.count-1)*pos)]+" "+self.codelist[int((self.count-1)*pos)]由于第二張過窄,我們就加點東西(" "+self.codelist[int((self.count-1)*pos))使它豐滿起來
本人水平有限,歡迎大家提出問題與建議。若代碼有看不懂的地方,也歡迎提出!
總結
以上是生活随笔為你收集整理的Python实战1- 图片转字符画的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python实战2 - 200行Pyth
- 下一篇: python爬虫系列:12306票务信息