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

前端之家收集整理的这篇文章主要介绍了没有对象?程序员的浪漫,对象攻略(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
原文链接:https://www.f2er.com/pythoninterview/997926.html

猜你在找的Python面试题相关文章