DEV Community

Cover image for Text overlay with Python
petercour
petercour

Posted on

3 1

Text overlay with Python

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.

#!/usr/bin/python3
# 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')
    cv2.imshow('src',src)
    cv2.waitKey(0)

    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'):
        cv2.destroyAllWindows()
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Then:

Related links:

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay