I have a 1:1 ratio image and I want to make sure that if the text exceeds the frame of the image, it gets wrapped to the next line.
How would I do it?
I am thinking of doing an if-else block, where "if sentence exceeds x characters->new line" but I'm not sure how to implement it.
import numpy as np
import cv2img = cv2.imread('images/1.png')
print(img.shape)height, width, channel = img.shapetext_img = np.ones((height, width))
print(text_img.shape)
font = cv2.FONT_HERSHEY_SIMPLEX
text = "Lorem Ipsum "
textsize = cv2.getTextSize(text, font, 2, 2)[0]font_size = 1
font_thickness = 2
for i, line in enumerate(text.split('\n')):textsize = cv2.getTextSize(line, font, font_size, font_thickness)[0]gap = textsize[1] + 10y = int((img.shape[0] + textsize[1]) / 2) + i * gapx = int((img.shape[1] - textsize[0]) / 2)cv2.putText(img, line, (x, y), font,font_size, (0,0,0), font_thickness, lineType = cv2.LINE_AA)cv2.imshow("Result Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
You can use textwrap
to wrap text in OpenCV.
import numpy as np
import cv2
import textwrap img = cv2.imread('apple.png')
print(img.shape)height, width, channel = img.shapetext_img = np.ones((height, width))
print(text_img.shape)
font = cv2.FONT_HERSHEY_SIMPLEXtext = "Lorem Ipsum dgdhswjkclyhwegflhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhvhasvcxsbvfajhskvfgsdj"
wrapped_text = textwrap.wrap(text, width=35)
x, y = 10, 40
font_size = 1
font_thickness = 2for i, line in enumerate(wrapped_text):textsize = cv2.getTextSize(line, font, font_size, font_thickness)[0]gap = textsize[1] + 10y = int((img.shape[0] + textsize[1]) / 2) + i * gapx = int((img.shape[1] - textsize[0]) / 2)cv2.putText(img, line, (x, y), font,font_size, (0,0,0), font_thickness, lineType = cv2.LINE_AA)cv2.imshow("Result Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Below is the output image without using textwrap
(running your code):
Below is the output image using textwrap
(my code):
There are many other ways you can achieve the same but textwrap
is certainly one way of doing so in OpenCV and is simple too.