Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
how to write multi line texts with opencv
import numpy as np
import cv2
import textwrap
img = np.zeros((500,500,3), dtype='uint8')
print(img.shape)
height, width, channel = img.shape
text_img = np.ones((height, width))
print(text_img.shape)
font = cv2.FONT_HERSHEY_SIMPLEX
text = "type: car, color: white, number: 123456"
#to automatically wrap text => wrapped_text = textwrap.wrap(text, width=10)
wrapped_text = ['Type: car','Color: white','Number: 123456']
x, y = 10, 40
font_size = 0.5
font_thickness = 1
i = 0
for line in wrapped_text:
textsize = cv2.getTextSize(line, font, font_size, font_thickness)[0]
gap = textsize[1] + 5
y = int((img.shape[0] + textsize[1]) / 2) + i * gap
x = 10#for center alignment => int((img.shape[1] - textsize[0]) / 2)
cv2.putText(img, line, (x, y), font,
font_size,
(255,255,255),
font_thickness,
lineType = cv2.LINE_AA)
i +=1
cv2.imshow("Result Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
@imneonizer

This comment has been minimized.

Copy link
Owner Author

imneonizer commented Sep 11, 2019

Example

import numpy as np
import cv2, imutils

frame_size = (1920, 1080)
canvas = np.zeros((frame_size[1], frame_size[0], 3),dtype='uint8')
#bbox box
X1,Y1,X2,Y2 = 100,200,400,400
canvas = cv2.rectangle(canvas, (X1,Y1), (X2,Y2), (255,255,255), 2)

#label box
#x1,y1,x2,y2 = X1-1, Y1-80, X2+1, Y1 #simple static height of label box
x1,y1,x2,y2 = X1-1, Y1-int(canvas.shape[1]*0.05), X2+1, Y1 #complex dynamic height of label box
canvas = cv2.rectangle(canvas, (x1,y1), (x2,y2), (255,255,255), -1)

cv2.imwrite('lable_box.jpg', canvas)
canvas = imutils.resize(canvas, width=500)
cv2.imshow('canvas', canvas)
cv2.waitKey(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.