Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing font family in OpenCV Python using PIL

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)
like image 356
Joe T. Boka Avatar asked Jun 15 '18 06:06

Joe T. Boka


1 Answers

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.

like image 80
fireant Avatar answered Oct 12 '22 05:10

fireant