Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ashwinning/0b85f9c151ee7013356f549bdeb7df48 to your computer and use it in GitHub Desktop.
Save Ashwinning/0b85f9c151ee7013356f549bdeb7df48 to your computer and use it in GitHub Desktop.
draw text with background // opencv
import cv2
class DrawText:
def __init__(self, img, text, font_scale = 1, posX = 10, posY = 10, font = cv2.FONT_HERSHEY_PLAIN, bgColor = (255, 255, 255), textColor = (0, 0, 0), fontThickness = 1, padding = 2):
self.font_scale = font_scale
self.font = font
rectangle_bgr = bgColor
# set some text
self.text = text
# get the width and height of the text box
(text_width, text_height) = cv2.getTextSize(text, font, fontScale=font_scale, thickness=fontThickness)[0]
# set the text start position
text_offset_x = posX
text_offset_y = img.shape[0] - posY
# make the coords of the box with a small padding of two pixels
box_coords = ((text_offset_x, text_offset_y), (text_offset_x + text_width - padding, text_offset_y - text_height - padding))
cv2.rectangle(img, box_coords[0], box_coords[1], rectangle_bgr, cv2.FILLED)
cv2.putText(img, text, (text_offset_x, text_offset_y), font, fontScale=font_scale, color=textColor, thickness=fontThickness)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment