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