Skip to content

Instantly share code, notes, and snippets.

@Erol444
Created September 4, 2022 21:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Erol444/962bf3d2bd5813d1475d03d154c9966b to your computer and use it in GitHub Desktop.
Save Erol444/962bf3d2bd5813d1475d03d154c9966b to your computer and use it in GitHub Desktop.
Center text on a OpenCV frame in Python
#!/usr/bin/env python
import cv2
import numpy as np
from enum import IntEnum
class Position(IntEnum):
"""
Where on frame do we want to print text.
"""
TopLeft = 0
MidLeft = 1
BottomLeft = 2
TopMid = 10
Mid = 11
BottomMid = 12
TopRight = 20
MidRight = 21
BottomRight = 22
def framePrint(frame, text: str, position: Position = Position.BottomLeft, padPx=10):
"""
Prints text on the frame.
@param frame: Frame
@param text: Text to be printed
@param position: Where on frame we want to print the text
@param padPx: Padding (in pixels)
"""
font = cv2.FONT_HERSHEY_SIMPLEX
textSize = cv2.getTextSize(text, font, fontScale=1.0, thickness=1)[0]
frameW = frame.shape[1]
frameH = frame.shape[0]
yPos = int(position) % 10
if yPos == 0: # Y Top
y = textSize[1] + padPx
elif yPos == 1: # Y Mid
y = int(frameH / 2) + int(textSize[1] / 2)
else: # yPos == 2. Y Bottom
y = frameH - padPx
xPos = int(position) // 10
if xPos == 0: # X Left
x = padPx
elif xPos == 1: # X Mid
x = int(frameW / 2) - int(textSize[0] / 2)
else: # xPos == 2 # X Right
x = frameW - textSize[0] - padPx
cv2.putText(frame, text, (x, y), font, fontScale=1.0, color=(255,255,255))
frame = np.zeros((600, 900, 3), np.uint8)
txt = "Hello World!"
framePrint(frame, 'TopLeft!', Position.TopLeft)
framePrint(frame, 'TopMid!', Position.TopMid)
framePrint(frame, 'TopRight!', Position.TopRight)
framePrint(frame, 'MidLeft!', Position.MidLeft)
framePrint(frame, 'Middle!', Position.Mid)
framePrint(frame, 'MidRight!', Position.MidRight)
framePrint(frame, 'BottomLeft!', Position.BottomLeft)
framePrint(frame, 'BottomMid!', Position.BottomMid)
framePrint(frame, 'BottomRight!', Position.BottomRight)
cv2.imshow('Frame', frame)
cv2.waitKey()
@MarcBresson
Copy link

you could just have a vertical align parameter and a horizontal align one

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment