身为一个程序员,时时刻刻都受到Bug的危害,有时候只靠自己总不是能万全无忧,这时候,有必要请护身符了!
先上效果。
转换后的效果
信我者,无Bug
为了实现图片转成字符文本,以下是具体思路:1.读入图片,将其转化为灰度图片2.逐行扫描像素点,转化为对应的字符。实施细节:1.根据灰阶,确定了8个字符,根据像素进行确认对应的字符,对应8个灰阶。2.字符在显示的时候长宽比不是一比一的,所以输入图片要首先经过调整,这里就是简单的高度除以2。3.用了PIL库
代码如下:
安装必要插件
pip install pillow
run.py代码
from img2ascii import *
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("inputpath",type =str ,help="Image file path")
parser.add_argument("-r",'--resize',type =float ,help="The zoom percentage for output,please use decimal")
args = parser.parse_args()
print(args.inputpath)
if not args.resize:
args.resize=1.0
else:
print(args.resize)
img = Img2ascii(args.inputpath,args.resize)
output = open(args.inputpath+'.txt','w')
for line in img.data:
print(line, file=output)
output.close()
print('Convert Done!')
img2ascii.py代码
from PIL import Image
class Img2ascii:
chars=[' ', ',', '+', '1', 'n','D','&','M']
def getchar(self,pi):
for i in range(0,8):
if pi< (i+1)*32:
return self.__class__.chars[7-i]
def __init__(self,src,resize=1.0):
img = Image.open(src)
if img.mode=='P' or img.mode =='RGBA':
im=Image.new('RGB',img.size,'white')
im.paste(img.convert('RGBA'),img.convert('RGBA'))
img= im
img= img.convert('L')
w,h =img.size
h/=2
w=int(w*resize)
h=int(h*resize)
img=img.resize((w,h),Image.ANTIALIAS)
img.save('tmp.jpg')
pixs = img.load()
self.data=[]
for i in range(0,h):
line =''
for j in range(0,w):
line+=self.getchar(pixs[j,i])
self.data.append(line)
执行:python3 run.py fo.jpeg -r 0.1
原图
转换后就是最终效果图啦。
代码库地址:https://gitee.com/python_play/image_to_textimg
感谢知乎作者:李白