Changing font family in OpenCV Python using PIL

夙愿已清 提交于 2020-07-21 03:54:05

问题


The above answer doesn't solve my problem.

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

This works as expected, but I am attempting to use a different font (not available in 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)

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

Here is the error:

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

回答1:


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)

The output of this screen is here.



来源:https://stackoverflow.com/questions/50870189/changing-font-family-in-opencv-python-using-pil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!