Last active
August 14, 2022 11:08
-
-
Save imneonizer/b64cdd8e2dc23451f5d8caf8279b3ff5 to your computer and use it in GitHub Desktop.
how to write multi line texts with opencv
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example