python 图片转字符(然并卵)
代码非常非常简单不做详细说明。
主要逻辑就是将图片转为灰度图,然后遍历像素获取灰度值匹配对应的字符,将拼接好的字符串输出到记事本文件。
(代码提供了两个方法,其实都差不多;记事本打开时要去掉自动换行,缩小字体大小,我打开是用宋体打开的)
1.[代码][Python]代码
from PIL import Image
import os
serarr=['@','#','$','%','&','?','*','o','/','{','[','(','|','!','^','~','-','_',':',';',',','.','`',' ']
count=len(serarr)
def toText(image_file):
image_file=image_file.convert("L")#转灰度
asd =''#储存字符串
for h in range(0, image_file.size[1]):#h
for w in range(0, image_file.size[0]):#w
gray =image_file.getpixel((w,h))
asd=asd+serarr[int(gray/(255/(count-1)))]
asd=asd+'\r\n'
return asd
def toText2(image_file):
asd =''#储存字符串
for h in range(0, image_file.size[1]):#h
for w in range(0, image_file.size[0]):#w
r,g,b =image_file.getpixel((w,h))
gray =int(r* 0.299+g* 0.587+b* 0.114)
asd=asd+serarr[int(gray/(255/(count-1)))]
asd=asd+'\r\n'
return asd
image_file = Image.open("convert.jpg") # 打开图片
image_file=image_file.resize((int(image_file.size[0]*0.9), int(image_file.size[1]*0.5)))#调整图片大小
print u'Info:',image_file.size[0],' ',image_file.size[1],' ',count
try:
os.remove('./tmp.txt')
except WindowsError:
pass
tmp=open('tmp.txt','a')
tmp.write(toText2(image_file))
tmp.close()
2.[图片] convert.jpg
3.[图片] 111.png
4.[代码]话说灰度值是0~256吗?!改了一下。反正我这里没问题。
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from PIL import Image
import os
serarr='''@#$%&?*aeoc=
count=len(serarr)
def toText(image_file):#此函数不能输入 gif 文件
image_file=image_file.convert("L")#转灰度
asd =''#储存字符串
for h in range(0, image_file.size[1]):#h
for w in range(0, image_file.size[0]):#w
gray =image_file.getpixel((w,h))
asd=asd+serarr[int(gray/(256/(count)))]
asd=asd+'\r\n'
return asd
def toText2(image_file):
asd =''#储存字符串
for h in range(0, image_file.size[1]):#h
for w in range(0, image_file.size[0]):#w
r,g,b =image_file.getpixel((w,h))
gray =int(r* 0.299+g* 0.587+b* 0.114)
asd=asd+serarr[int(gray/(256/(count)))]
asd=asd+'\r\n'
return asd
image_file = Image.open("hehe.jpg") # 打开图片
image_file=image_file.resize((int(image_file.size[0]*0.9), int(image_file.size[1]*0.5)))#调整图片大小
print u'Info:',image_file.size[0],' ',image_file.size[1],' ',count
tmp=open('tmp.txt','w')
tmp.write(toText(image_file))
tmp.close()