手把手教你如何将图片转换成字符画

步骤:

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. 如果你用记事本打开输出文件,记得关闭自动换行

如需转载请注明出处哟

喜欢就支持一下呗~

posted @ 2018-06-06 10:34  MartinLwx  阅读(9430)  评论(0编辑  收藏  举报