目前,我可以使用 openCV API (putText) 将一些 HERSHEY 字体的文本插入到图像中。但是 openCV 似乎不支持任何等宽字体。
我想知道如何在图像中插入一些 Monospace 或固定间距文本。
最佳答案
您可以很容易地在这方面使用 PIL/Pillow。 OpenCV 图像是 numpy
数组,因此您可以使用以下方法从 OpenCV 图像制作 Pillow Image:
PilImage = Image.fromarray(OpenCVimage)
然后您可以使用我的答案中的代码使用单间距字体绘制 here .您只需要注释 “获取绘图上下文” 之后的 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)
或者,您可以让一个函数自己生成一 block Canvas ,在上面写下您的文本,然后将它拼接到您想要的任何位置的 OpenCV 图像中。这些方面的东西 - 虽然我不知道你需要什么样的灵 active ,所以我没有参数化一切:
#!/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。
关于python - 如何使用 opencv 将 Monospace 字体插入到图像中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53696243/