DEV Community

Cover image for Text overlay with Python

Text overlay with Python

・2 min read

you can to overlay text on images. This is pretty easy. One way is with OpenCv (cv2), The computer vision module. But it's quite a large module, perhaps it's better to use PIL or something for this task.

So say you go with OpenCV. The difficult part is to install the OpenCv module. Some guides recommend to compile the whole module.

Install on Ubuntu

On Ubuntu there's an unofficial module you can install from the repository, problem with that one is that it doesn't work with Python 3.6.

Either way once installed you can run the code.

# coding=utf-8
import cv2
import numpy
from PIL import Image, ImageDraw, ImageFont

def cv2ImgAddText(img, text, left, top, textColor=(0, 255, 0), textSize=20):
    if (isinstance(img, numpy.ndarray)): 
        img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
        draw = ImageDraw.Draw(img) 
        fontStyle = ImageFont.truetype( "FreeSans.ttf", textSize, encoding="utf-8") 
        draw.text((left, top), text, textColor, font=fontStyle)
        return cv2.cvtColor(numpy.asarray(img), cv2.COLOR_RGB2BGR)

if __name__ == '__main__':
    src = cv2.imread('img1.jpg')

    img = cv2ImgAddText(src, "Python programmers taking a walk", 10, 35, (255, 255 , 255), 20)
    cv2.imshow('show', img)
    if cv2.waitKey(0) & 0xFF == ord('q'):

The image img1.jpg can be any input image. I picked this one:

The text color overlay is white (255,255,255). These numbers are 0 to 255 for color channels.

    img = cv2ImgAddText(src, "Python programmers taking a walk", 10, 35, (255, 255 , 255), 20)


Related links:

Discussion (0)