廢話少說,直接上圖:




理論:
對圖片灰度值以及字符的灰度值都做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, 4)]
imagefile = base.resize