gpt4 book ai didi

python - 使用 PIL 更改 OpenCV Python 中的字体系列

转载 作者:太空宇宙 更新时间:2023-11-03 21:10:41 25 4
gpt4 key购买 nike

以上回答没有解决我的问题。

我正在使用 cv2.putText() 将文本放在视频上。

这按预期工作,但我正在尝试使用不同的字体(在 OpenCV 中不可用)。

我知道 OpenCV 仅限于 cv2.FONT_HERSHEY 字体,所以我使用 PIL 和 OpenCV 来实现这一点。

我对图像使用了这种方法,实验成功了。但是当我在视频上尝试类似的东西时我失败了。

import cv2
from PIL import ImageFont, ImageDraw, Image

camera = cv2.VideoCapture('some_video.wmv')
while cv2.waitKey(30) < 0:
rv, frame = camera.read()
if rv:
font = ImageFont.truetype("calibrii.ttf", 80)
cv2.putText(frame, 'Hello World!', (600, 600), font, 2.8, 255)
cv2.imshow('Video', frame)

我在同一目录中有“calibrii.ttf”,正如我提到的,这种方法适用于图像。

这里是错误:

cv2.putText(frame, 'Hello World!', (600, 600), font, 2.8, 255)
TypeError: an integer is required (got type FreeTypeFont)

最佳答案

您可以使用 OpenCV 的 freetype 模块来执行此操作,无需使用 PIL。

import cv2
import numpy as np

img = np.zeros((100, 300, 3), dtype=np.uint8)

ft = cv2.freetype.createFreeType2()
ft.loadFontData(fontFileName='Ubuntu-R.ttf',
id=0)
ft.putText(img=img,
text='Quick Fox',
org=(15, 70),
fontHeight=60,
color=(255, 255, 255),
thickness=-1,
line_type=cv2.LINE_AA,
bottomLeftOrigin=True)

cv2.imwrite('image.png', img)

这个屏幕的输出是here .

关于python - 使用 PIL 更改 OpenCV Python 中的字体系列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50870189/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com