python - 当我在图像上打印文本并且它超出了图像的框架时,如何在 OpenCV 中包装文本?

标签 python python-3.x opencv

我有一个 1:1 比例的图像,我想确保如果文本超出图像的框架,它会换行到下一行。 我该怎么做?

我正在考虑做一个 if-else block ,其中“if sentence exceeds x characters->new line”但我不确定如何实现它。

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

最佳答案

您可以使用 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

for i, line in enumerate(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)

cv2.imshow("Result Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

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

enter image description here

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

enter image description here

还有许多其他方法可以实现相同的目的,但 textwrap 无疑是 OpenCV 中的一种方法,而且也很简单。

关于python - 当我在图像上打印文本并且它超出了图像的框架时,如何在 OpenCV 中包装文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56660241/

相关文章:

python - Python 中是否有等同于 Typescript 感叹号的东西?

python - 如何在Python中提供输入流?

python - 如何按 pandas 中的列创建聚合?

android - 如何理解OpenCV程序中引发的此异常

c++ - 调试断言失败

python - scikit-learn MLPRegressor中如何判断哪一个是训练和测试?

python - 带有 bool 语句的 Numpy 向量化函数赋值

python - Python 中带模式的字数统计

python - 网页抓取 ~ Python

opencv - 查找仿射变换图像中像素 block 相对于原始引用的方向