How to wrap text in OpenCV when I print it on an image and it exceeds the frame of the image?

2024/9/16 23:16:51

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()
Answer

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):

enter image description here

Below is the output image using textwrap(my code):

enter image description here

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.

https://en.xdnf.cn/q/72721.html

Related Q&A

pandas series filtering between values

If s is a pandas.Series, I know I can do this:b = s < 4or b = s > 0but I cant dob = 0 < s < 4orb = (0 < s) and (s < 4)What is the idiomatic pandas method for creating a boolean series…

python os.path.exists reports False when files is there

Hi have an application which is sometimes reporting that a file does not exist even when it does, I am using os.path.exists and the file is on a mounted network share. I am on OSX Yosemite, python 2.7.…

Python unhashable type: numpy.ndarray

I worked on making functions for K Nearest Neighbors. I have tested each function separately and they all work well. However whenever I put them together and run KNN_method, it shows unhashable type: n…

Efficient way to generate Lime explanations for full dataset

Am working on a binary classification problem with 1000 rows and 15 features. Currently am using Lime to explain the predictions of each instance. I use the below code to generate explanations for full…

how to handle javascript alerts in selenium using python

So I there is this button I want to click and if its the first time youve clicked it. A javascript alert popup will appear. Ive been using firebug and just cant find where that javascript is located an…

testing.postgresql command not found: initdb inside docker

Hi im trying to make a unittest with postgresql database that use sqlalchemy and alembicAlso im running it on docker postgresqlIm following the docs of testing.postgresql(docs) to set up a temporary po…

Recommended approach for loading CouchDB design documents in Python?

Im very new to couch, but Im trying to use it on a new Python project, and Id like to use python to write the design documents (views), also. Ive already configured Couch to use the couchpy view server…

Error when import matplotlib.pyplot as plt

I did not have any problem to use "plt", but it suddenly shows an error message and does not work, when I import it. Please see the below. >>> import matplotlib >>> import m…

Python NtQueryDirectoryFile (File information structure)

Ive written a simple (test) script to list files in a selected directory. Not using FindFirstFile; only native API. When I execute the script and watch, Win32API monitor tells me STATUS_SUCCESS. My Fil…

returning A DNS record in dnspython

I am using dnspython to get the A record and return the result (IP address for a given domain).I have this simple testing python script:import dns.resolverdef resolveDNS():domain = "google.com&quo…