如何使用 opencv 将 Monospace 字体插入到图像中?

How can I insert Monospace fonts into an image with opencv?

目前,我可以使用 openCV API (putText) 将一些 HERSHEY 字体的文本插入到图像中。但是openCV似乎不支持任何等宽字体。

我想知道如何在图像中插入一些等宽或固定间距的文本。

您可以很容易地在这方面使用 PIL/Pillow。 OpenCV 图像是 numpy 数组,因此您可以使用以下命令从 OpenCV 图像制作枕头图像:

PilImage = Image.fromarray(OpenCVimage)

然后你可以使用我的答案中的代码使用等宽字体绘制 。您只需要注释 "Get a drawing context".

之后的 3 行

然后您可以使用以下方法转换回 OpenCV 图像:

OpenCVimage = np.array(PilImage)

可能看起来像这样:

#!/usr/local/bin/python3

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

# Open image with OpenCV
im_o = cv2.imread('start.png')

# Make into PIL Image
im_p = Image.fromarray(im_o)

# Get a drawing context
draw = ImageDraw.Draw(im_p)
monospace = ImageFont.truetype("/Library/Fonts/Andale Mono.ttf",32)
draw.text((40, 80),"Hopefully monospaced",(255,255,255),font=monospace)

# Convert back to OpenCV image and save
result_o = np.array(im_p)
cv2.imwrite('result.png', result_o)


或者,你可以让一个函数自己生成一个 canvas 块,在上面写下你的文本,然后将它拼接到你想要的任何地方的 OpenCV 图像中。这些方面的东西 - 虽然我不知道你需要什么样的灵活性所以我没有参数化一切:

#!/usr/local/bin/python3

from PIL import Image, ImageFont, ImageDraw, ImageColor
import numpy as np
import cv2


def GenerateText(size, fontsize, bg, fg, text):
   """Generate a piece of canvas and draw text on it"""
   canvas = Image.new('RGB', size, bg)

   # Get a drawing context
   draw = ImageDraw.Draw(canvas)
   monospace = ImageFont.truetype("/Library/Fonts/Andale Mono.ttf",fontsize)
   draw.text((10, 10), text, fg, font=monospace)

   # Change to BGR order for OpenCV's peculiarities
   return cv2.cvtColor(np.array(canvas), cv2.COLOR_RGB2BGR)


# Open image with OpenCV
im_o = cv2.imread('start.png')


# Try some tests
w,h = 350,50
a,b = 20, 80
text = GenerateText((w,h), 32, 'black', 'magenta', "Magenta on black")
im_o[a:a+h, b:b+w] = text


w,h = 200,40
a,b = 120, 280
text = GenerateText((w,h), 18, 'cyan', 'blue', "Blue on cyan")
im_o[a:a+h, b:b+w] = text

cv2.imwrite('result.png', im_o)

关键字: OpenCV, Python, Numpy, PIL, Pillow, image, image processing, monospace, font, fonts, fixed, fixed width, courier, HERSHEY .