OpenCV cv2.putText实现字符串换行'\n'
OpenCV显示字符串时,可以调用cv2.putText直接进行显示方法,但该函数是不支持换行符"\n"的
要想实现自动换行,需要自己编程计算字符宽度,下移动宽度等操作
这里提供自己实现draw_text_line()函数,可以直接支持换行符的显示
代码实现:
-
# -*-coding: utf-8 -*-
-
"""
-
@Project: Demo
-
@Author : panjq
-
@E-mail : pan_jinquan@163.com
-
@Date : 2019-12-11 19:43:34
-
"""
-
import cv2
-
-
-
def draw_text(img, point, text, drawType="custom"):
-
'''
-
:param img:
-
:param point:
-
:param text:
-
:param drawType: custom or custom
-
:return:
-
'''
-
fontScale =
0.4
-
thickness =
5
-
text_thickness =
1
-
bg_color = (
255,
0,
0)
-
fontFace = cv2.FONT_HERSHEY_SIMPLEX
-
# fontFace=cv2.FONT_HERSHEY_SIMPLEX
-
if drawType ==
"custom":
-
text_size, baseline = cv2.getTextSize(str(text), fontFace, fontScale, thickness)
-
text_loc = (point[
0], point[
1] + text_size[
1])
-
cv2.rectangle(img, (text_loc[
0] -
2 //
2, text_loc[
1] -
2 - baseline),
-
(text_loc[
0] + text_size[
0], text_loc[
1] + text_size[
1]), bg_color,
-1)
-
# draw score value
-
cv2.putText(img, str(text), (text_loc[
0], text_loc[
1] + baseline), fontFace, fontScale,
-
(
255,
255,
255), text_thickness,
8)
-
elif drawType ==
"simple":
-
cv2.putText(img,
'%d' % (text), point, fontFace,
0.5, (
255,
0,
0))
-
return img
-
-
-
def draw_text_line(img, point, text_line: str, drawType="custom"):
-
'''
-
:param img:
-
:param point:
-
:param text:
-
:param drawType: custom or custom
-
:return:
-
'''
-
fontScale =
0.4
-
thickness =
5
-
fontFace = cv2.FONT_HERSHEY_SIMPLEX
-
# fontFace=cv2.FONT_HERSHEY_SIMPLEX
-
text_line = text_line.split(
"\n")
-
# text_size, baseline = cv2.getTextSize(str(text_line), fontFace, fontScale, thickness)
-
text_size, baseline = cv2.getTextSize(str(text_line), fontFace, fontScale, thickness)
-
for i, text
in enumerate(text_line):
-
if text:
-
draw_point = [point[
0], point[
1] + (text_size[
1] +
2 + baseline) * i]
-
img = draw_text(img, draw_point, text, drawType)
-
return img
-
-
-
if __name__ ==
"__main__":
-
import copy
-
image_path =
"./data/test/test01.jpg"
-
image = cv2.imread(image_path)
-
point = (
10,
10)
-
text_line =
"AAAA\nBBBB\nCCCC\n"
-
image1 = draw_text(copy.copy(image), point, text_line, drawType=
"custom")
-
cv2.imshow(
"draw_text", image1)
-
image2 = draw_text_line(copy.copy(image), point, text_line)
-
cv2.imshow(
"draw_text_line", image2)
-
cv2.waitKey(
0)
-
cv2.waitKey(
0)
转载:https://blog.csdn.net/guyuealian/article/details/103498851
查看评论