如何使用 PIL(或其他任何东西)将图像动态调整为文本大小?

时间:2021-01-03 01:09:53

标签: python python-imaging-library

我希望我创建的图像的大小根据写入其中的字符串动态更改。我的代码目前所做的是,使用 PIL 和 docx 实现,从我放入单个字符串的 word 文档中获取数据,然后通过一些循环对其进行解析,以便为字符串中的特定文本摘录输出图像,即从关键字一直到零件编号。为了仅显示完全必要的内容,以下是我需要帮助的代码部分:

for match in find_matches(text=docText, keywords=("responsive", "detecting", "providing")):
    W, H = 300, 300
    body = Image.new('RGB', (W, H), (255, 255, 255))
    border = Image.new('RGB', (W + 4, H + 4), (0, 0, 0))
    border.save('border.png')
    body.save('body.png')
    patent = Image.open('border.png')
    patent.paste(body, (2, 2))
    draw = ImageDraw.Draw(patent)
    font = ImageFont.load_default()
    current_h, pad = 100, 20

    for key in textwrap.wrap(match, width=45):
        line = key.encode('utf-8')
        w, h = draw.textsize(line, font=font)
        draw.text(((W - w) / 2, current_h), line, (0, 0, 0), font=font)
        current_h += h + pad
    for count, matches in enumerate(match):
        patent.save(f'{match}.png')

从这个和我的其余代码中,我也有这个源文档文件,我将只显示一个图像:

Source Doc

最后,根据我现有的代码,我可以获得以下图像输出:

enter image description here enter image description here enter image description here enter image description here

目标是能够从图像中删除所有空白,或尽可能多地删除,并将其添加到创建图像的自动化过程中,以便尽可能少的空白使图像边框以相同的类似框的格式适合文本周围。作为额外的奖励,这根本不是必需的,因为我主要是询问空格问题,如果有一个快速修复方法可以使“249C”和类似的零件编号在最后一行没有其他文本加入他们,这也很好,但我的主要问题是使图像适合文本的大小。

这是我希望我的输出看起来像什么的一个例子,除了每个框都是它自己的图像:

Sample Output

1 个答案:

答案 0 :(得分:0)

您似乎可以完全控制图像上的文本,这意味着如果您将文本添加到具有白色背景的图像中,您就可以准确知道黑色像素的位置。有了这张图片,你可以通过计算每行/每列中的黑色像素来确定“边框”,你可以得到边框的位置。

例如:

image  = cv2.imread("image-file")
grayImage = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
nrows, ncols = grayImage.shape
isBlackPixelMat = grayImage < 100
numOfPixelInColumn = isBlackPixelMat.sum(axis=0)

# find start column
k = 0;
while k < ncols and numOfPixelInColumn[k] == 0:
    k += 1
startColumn = k

# find end column
k = ncols - 1

while k > 0 and numOfPixelInColumn[k] == 0:
    k -= 1
endColumn = k

# draw lines

cv2.line(image, (startColumn, 0), (startColumn, ncols - 1), color=(255, 0, 0))
cv2.line(image, (endColumn, 0), (endColumn, ncols - 1), color=(255, 0, 0))

enter image description here

相关问题