Python-呈现倾斜字体

问题描述 投票:0回答:1

此问题与我在Stackoverflow中的previous question中的答案一致。

我正在创建一个将文本转换为图像的程序。我想使用字体OCR A进行渲染。但是由于OCR A字体没有对应的斜体字体文件,因此我必须手动进行直立字体的倾斜。

enter image description here

直立字体

enter image description here

倾斜字体

下面是我的初始代码:

 from PIL import Image
 from PIL import ImageDraw
 from PIL import ImageFont
 import numpy as np


 #Returns the text size in terms of width and height.
 def getSize(txt, font):
     testImg = Image.new('RGB', (1, 1))
     testDraw = ImageDraw.Draw(testImg)
     return testDraw.textsize(txt, font)

 text = 'CNN Font Recognition Model'
 font_size = 12
 font = ImageFont.truetype('ocra.ttf' , font_size)  
 #ocra.ttf is a font file for OCR A Regular font (I have to render it slanted) 

 width, height = getSize(text, font)

 #Creates an image with white background of constant size.
 img = Image.new('RGB',(width, height), 'white')
 d = ImageDraw.Draw(img)
 d.text((0,0), text, fill='black', font=font)
 img.save('slanted_ocr_a.png')

如何手动倾斜直立的OCR A字体?谢谢。您可以下载样本ocra.ttf文件here.

python python-3.x image image-processing fonts
1个回答
0
投票

This answer到类似的问题可能是最简单的方法,尽管这并不是您想要的。基本上,您将直立字体呈现为图像,然后使用PIL的Image.transform方法倾斜(剪切)整个图像。

要精确地完成您所要的内容(使字体之前成像),但是要使PIL的truetype方案具有基础字体引擎(FreeType)perform the slant transformation at the font level,需要大量工作。 PIL的truetype接口根本没有表达转换的方法,因此您必须重写/修补它才能将其一直传递到设置字体的FreeType。

© www.soinside.com 2019 - 2024. All rights reserved.