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

标签 python opencv python-imaging-library opencv-python

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

我正在使用 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/

相关文章:

python - 如何在纯 python 或 : How to bind the key left of the [1] to a shortcut in Qt 中从硬件键号/扫描码获取实际键名

python - 如何使用python中的tkinter上的保存按钮保存图像

python - PIL库导入失败

python PIL : How to save cropped image?

python - 名称和函数体如何存储在 Python 代码对象中?

从列表中设置路径的Pythonic方式

python - 为什么 Python 列表理解过滤器对 if-else 有不同的语法

xcode - 在 Xcode 中链接 OpenCV 时出现体系结构 x86_64 错误的 undefined symbol

c++ - 使用 OpenCV 和 C++ 实现 SURF 时出现错误 cv::SURF::SURF(double,int,int,bool,bool)

c++ - 用户自定义类型的 OpenCV 矩阵