我如何在opencv中将等宽字体插入图像中?

2024-10-03 09:17:46 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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


Tags: 图像文本字体opencv间距puttexthersheyopencvapi
1条回答
网友
1楼 · 发布于 2024-10-03 09:17:46

你可以很容易地用枕头/枕头。OpenCV图像是numpy数组,因此可以使用以下内容从OpenCV图像制作枕头图像:

PilImage = Image.fromarray(OpenCVimage)

然后你可以用我的答案here中的代码用单倍行距字体绘制。您只需要注释“Get a drawing context”后的3行。在

然后,可以使用以下命令转换回OpenCV图像:

^{pr2}$

可能是这样的:

#!/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)

enter image description here


或者,你可以让一个函数生成一块画布,在上面写上你的文本,然后把它拼接到你想要的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)

enter image description here

关键词:OpenCV、Python、Numpy、PIL、pill、图像、图像处理、monospace、字体、字体、固定宽度、courier、HERSHEY。在

相关问题 更多 >