目前,我可以使用 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)
或者,你可以让一个函数自己生成一块画布,在上面写下你的文本,然后将它拼接到你想要的任何地方的 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、枕头、图像、图像处理、等宽、字体、字体、固定、固定宽度、快递、好时。