废话少说,直接上图:
理论:
对图片灰度值以及字符的灰度值都做histogram,并进行主要部分的对应,可以改善对比度和显示效果
经过我在网上拼拼凑凑,以及自己稍微改改得到的代码如下:
PIL库:
只需要安装pillow库就行了。以下是终端安装代码:
pip install pillow
- 1
完整源码:
from PIL import Image,ImageDraw,ImageFont
import operator,bisect
def getChar(val):
index @H_403_59@= bisect.bisect_left(scores,val)
if index @H_403_59@> 0 @H_403_59@and sorted_weights[index][1] @H_403_59@+ sorted_weights[index @H_403_59@-
1][1] @H_403_59@> 2 @H_403_59@* val:
index @H_403_59@-= 1
return sorted_weights[index][0]
def transform(image_file):
image_file @H_403_59@= image_file.convert("L")
codePic @H_403_59@= ''
for h in range(image_file.size[1]):
for w in range(image_file.size[0]):
gray @H_403_59@= image_file.getpixel((w,h))
codePic @H_403_59@+= getChar(maximum @H_403_59@* (1 @H_403_59@- gray @H_403_59@/ 255))
codePic @H_403_59@+= '\r\n'
return codePic
PictureName @H_403_59@= input("请输入您要转换的照片名称:")
readinFilePath @H_403_59@= f'{PictureName}'
outputTextFile @H_403_59@= f'{PictureName}_ascii.txt'
outputImageFile @H_403_59@= f'{PictureName}_ascii.jpg'
fnt @H_403_59@= ImageFont.truetype('Courier New.ttf',10)
chrx,chry @H_403_59@= fnt.getsize(chr(32))
normalization @H_403_59@= chrx @H_403_59@* chry @H_403_59@* 255
weights @H_403_59@= {}
for i in range(32,127):
chrImage @H_403_59@= fnt.getmask(chr(i))
sizex,sizey @H_403_59@= chrImage.size
ctr @H_403_59@= sum(
chrImage.getpixel((x,y)) for y in range(sizey) for x in range(sizex))
weights[chr(i)] @H_403_59@= ctr @H_403_59@/ normalization
weights[chr(32)] @H_403_59@= 0.01
weights.pop('_',None)
weights.pop('-',None)
sorted_weights @H_403_59@= sorted(weights.items(),key@H_403_59@=operator.itemgetter(1))
scores @H_403_59@= [y for (x,y) in sorted_weights]
maximum @H_403_59@= scores[@H_403_59@-1]
base @H_403_59@= Image.open(open(readinFilePath,'rb'))
resolution @H_403_59@= 0.3
sizes @H_403_59@= [resolution @H_403_59@* i for i in (0.665,0.3122