微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

没有对象?程序员的浪漫,对象攻略1

废话少说,直接上图:

在这里插入图片描述


在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

理论:

对图片灰度值以及字符的灰度值都做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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐