使用PIL在OpenCV Python中更改字体系列 [英] Changing font family in OpenCV Python using PIL

查看:645
本文介绍了使用PIL在OpenCV Python中更改字体系列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用cv2.putText()在视频上放置文字.

I am using cv2.putText() to put text over a video.

这可以按预期工作,但是我尝试使用其他字体(在OpenCV中不可用).

This works as expected, but I am attempting to use a different font (not available in OpenCV).

我了解OpenCV仅限于cv2.FONT_HERSHEY字体,因此我将PIL与OpenCV配合使用来实现此目的.

I understand that OpenCV is limited to the cv2.FONT_HERSHEY fonts, so I am using PIL with OpenCV to achieve this.

我将此方法用于图像,并且实验成功.但是当我在视频上尝试类似的操作时,我就失败了.

I used this method with images and that experiment was successful. But I am failing when I try something similar on a video.

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"在我提到的同一目录中,此方法适用于图像.

I have the "calibrii.ttf" in the same directory and as I mentioned, this approach worked with images.

这是错误:

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

推荐答案

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

You can use OpenCV's freetype module to do so, no need to use 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)

此屏幕的输出是此处

这篇关于使用PIL在OpenCV Python中更改字体系列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆