您可以很容易地使用 PIL/Pillow 来实现这一点。OpenCV 图像是numpy
数组,因此您可以使用以下命令从 OpenCV 图像制作枕头图像:
PilImage = Image.fromarray(OpenCVimage)
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用我的答案中的代码使用单倍间距字体进行绘制。您只需要注释“获取绘图上下文”后的 3 行。
然后你可以使用以下命令转换回 OpenCV 图像:
OpenCVimage = np.array(PilImage)
Run Code Online (Sandbox Code Playgroud)
请注意,您不仅限于等宽字体,您可以使用任何您喜欢的 Truetype 字体。
这可能看起来像这样:
#!/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)
Run Code Online (Sandbox Code Playgroud)
或者,您可以让一个函数本身生成一块画布,在上面写下您的文本,然后将其拼接到您想要的 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)
Run Code Online (Sandbox Code Playgroud)
关键词:OpenCV、Python、Numpy、PIL、Pillow、图像、图像处理、等宽、字体、字体、固定、固定宽度、快递、好时。