当我将文本打印在图像上并且超出图像的框架时,如何在 OpenCV 中换行? [英] How to wrap text in OpenCV when I print it on an image and it exceeds the frame of the image?

查看:76
本文介绍了当我将文本打印在图像上并且超出图像的框架时,如何在 OpenCV 中换行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

我正在考虑做一个 if-else 块,其中如果句子超过 x 个字符-> 换行",但我不知道如何实现它.

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 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 中对文本进行换行.

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.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(运行你的代码)的输出图像:

Below is the output image without using textwrap(running your code):

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

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

您可以通过许多其他方法实现相同的目标,但 textwrap 无疑是 OpenCV 中实现此目的的一种方法,而且也很简单.

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.

这篇关于当我将文本打印在图像上并且超出图像的框架时,如何在 OpenCV 中换行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆