Skip to content

Instantly share code, notes, and snippets.

@ekapujiw2002
Forked from xcsrz/center_text_on_image.py
Created July 3, 2018 04:12
Show Gist options
  • Save ekapujiw2002/1bc4722ae186ddf8f9b8070dd3107a34 to your computer and use it in GitHub Desktop.
Save ekapujiw2002/1bc4722ae186ddf8f9b8070dd3107a34 to your computer and use it in GitHub Desktop.
Center text on an image with Python and OpenCV. Had to come up with it myself as no one was spelling this out anywhere (or google couldn't find it)
#!/usr/bin/env python
import numpy as np
import cv2
from time import sleep
# create blank image - y, x
img = np.zeros((600, 1000, 3), np.uint8)
# setup text
font = cv2.FONT_HERSHEY_SIMPLEX
text = "Hello Joseph!!"
# get boundary of this text
textsize = cv2.getTextSize(text, font, 1, 2)[0]
# get coords based on boundary
textX = (img.shape[1] - textsize[0]) / 2
textY = (img.shape[0] + textsize[1]) / 2
# add text centered on image
cv2.putText(img, text, (textX, textY ), font, 1, (255, 255, 255), 2)
# display image
cv2.imshow('image', img)
# wait so you can see the image
sleep(25)
# cleanup
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment