当我在图像上打印超出文本框架的文本时,如何在OpenCV中换行?

Abh*_*ava 2 python opencv python-3.x

我有一个1:1比例的图像,并且我想确保如果文本超出图像的框架,则将其包裹到下一行。我该怎么办?

我正在考虑做一个if-else块,其中“如果句子超过x个字符->换行”,但是我不确定如何实现它。

import numpy as np
import cv2

img = cv2.imread('images/1.png')
print(img.shape)

height, width, channel = img.shape

text_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] + 10

    y = int((img.shape[0] + textsize[1]) / 2) + i * gap
    x = 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()
Run Code Online (Sandbox Code Playgroud)

Anu*_*ngh 7

您可以用来textwrap在OpenCV中换行。

import numpy as np
import cv2
import textwrap 

img = cv2.imread('apple.png')
print(img.shape)

height, width, channel = img.shape

text_img = np.ones((height, width))
print(text_img.shape)
font = cv2.FONT_HERSHEY_SIMPLEX

text = "Lorem Ipsum dgdhswjkclyhwegflhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhvhasvcxsbvfajhskvfgsdj"
wrapped_text = textwrap.wrap(text, width=35)
x, y = 10, 40
font_size = 1
font_thickness = 2

i = 0
for line in wrapped_text:
    textsize = cv2.getTextSize(line, font, font_size, font_thickness)[0]

    gap = textsize[1] + 10

    y = int((img.shape[0] + textsize[1]) / 2) + i * gap
    x = 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)
    i +=1

cv2.imshow("Result Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Run Code Online (Sandbox Code Playgroud)

下面是未使用textwrap(运行代码)的输出图像:

在此处输入图片说明

下面是使用textwrap(我的代码)的输出图像:

在此处输入图片说明

您可以通过许多其他方法来实现相同的目标,但textwrap肯定是OpenCV中实现这一目标的一种方法,而且也很简单。