Text on image in custom font in Python using PIL and OpenCV
In this article, we have explained how to use custom font in Python, OpenCV to write text over an image. This uses PIL (Python Imaging Library).
Table of contents:
- Text on image in custom font
- Complete Python code
Text on image in custom font
OpenCV provides a set of standard fonts that a developer can use to write text on an image. Unfortunately, it is not possible in OpenCV to use a font beyond the standard set.
The alternative is to use Python Imaging Library (PIL) which has the support to use custom fonts to write text over images. Once the text is written over the image using PIL, the image can be transferred back to be used by OpenCV.
To install PIL in your system:
pip install pillow
Download the font file of the Font you want to use. You need to convert the font file to TTF format. Usually, it is downloadable in OTF format so you need to convert it to TTF format.
The font file say cyrillic.ttf is kept locally to be used by your script.
Import the relevant libraries:
import cv2
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
Load the image in the form required by ImageDraw of PIL:
image = np.load("image.jpeg")
image = Image.fromarray(image)
draw = ImageDraw.Draw(image)
Load the custom font:
font_size = 10
font = ImageFont.truetype("localfont.ttf", font_size)
Draw the text on the image:
text = "opengenus"
draw.text((width, height), str(text), font=font)
(width, height) is the left top-most point of the text. You shall give the point correctly to have the text on the correct location. Note that the text will be written on a single line irrespective of the length of the text.
If the text cannot fit on a single line on the image, then part of the text that goes outside the image is not printed.
You need to switch to the next line with a new dimension to accomodate longer sentences.
Convert the image back to OpenCV format if you need to use OpenCV function for some functions:
image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
Once everything is done, save the image with text:
image = Image.fromarray(image)
image_filename = "opengenus_image.jpeg"
image.save(image_filename)
Complete Python code
Following is the complete Python code to write Text on image in custom font in Python using PIL and OpenCV:
import cv2
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
image = np.load("image.jpeg")
image = Image.fromarray(image)
draw = ImageDraw.Draw(image)
font_size = 10
font = ImageFont.truetype("localfont.ttf", font_size)
text = "opengenus"
draw.text((width, height), str(text), font=font)
image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
image = Image.fromarray(image)
image_filename = "opengenus_image.jpeg"
image.save(image_filename)
With this article at OpenGenus, you must have the complete idea of how to write Text on image in custom font in Python using PIL and OpenCV.