小言_互联网的博客

OpenCV cv2.putText实现字符串换行'\n'

953人阅读  评论(0)

OpenCV cv2.putText实现字符串换行'\n'

OpenCV显示字符串时,可以调用cv2.putText直接进行显示方法,但该函数是不支持换行符"\n"的

要想实现自动换行,需要自己编程计算字符宽度,下移动宽度等操作

这里提供自己实现draw_text_line()函数,可以直接支持换行符的显示

代码实现:


  
  1. # -*-coding: utf-8 -*-
  2. """
  3. @Project: Demo
  4. @Author : panjq
  5. @E-mail : pan_jinquan@163.com
  6. @Date : 2019-12-11 19:43:34
  7. """
  8. import cv2
  9. def draw_text(img, point, text, drawType="custom"):
  10. '''
  11. :param img:
  12. :param point:
  13. :param text:
  14. :param drawType: custom or custom
  15. :return:
  16. '''
  17. fontScale = 0.4
  18. thickness = 5
  19. text_thickness = 1
  20. bg_color = ( 255, 0, 0)
  21. fontFace = cv2.FONT_HERSHEY_SIMPLEX
  22. # fontFace=cv2.FONT_HERSHEY_SIMPLEX
  23. if drawType == "custom":
  24. text_size, baseline = cv2.getTextSize(str(text), fontFace, fontScale, thickness)
  25. text_loc = (point[ 0], point[ 1] + text_size[ 1])
  26. cv2.rectangle(img, (text_loc[ 0] - 2 // 2, text_loc[ 1] - 2 - baseline),
  27. (text_loc[ 0] + text_size[ 0], text_loc[ 1] + text_size[ 1]), bg_color, -1)
  28. # draw score value
  29. cv2.putText(img, str(text), (text_loc[ 0], text_loc[ 1] + baseline), fontFace, fontScale,
  30. ( 255, 255, 255), text_thickness, 8)
  31. elif drawType == "simple":
  32. cv2.putText(img, '%d' % (text), point, fontFace, 0.5, ( 255, 0, 0))
  33. return img
  34. def draw_text_line(img, point, text_line: str, drawType="custom"):
  35. '''
  36. :param img:
  37. :param point:
  38. :param text:
  39. :param drawType: custom or custom
  40. :return:
  41. '''
  42. fontScale = 0.4
  43. thickness = 5
  44. fontFace = cv2.FONT_HERSHEY_SIMPLEX
  45. # fontFace=cv2.FONT_HERSHEY_SIMPLEX
  46. text_line = text_line.split( "\n")
  47. # text_size, baseline = cv2.getTextSize(str(text_line), fontFace, fontScale, thickness)
  48. text_size, baseline = cv2.getTextSize(str(text_line), fontFace, fontScale, thickness)
  49. for i, text in enumerate(text_line):
  50. if text:
  51. draw_point = [point[ 0], point[ 1] + (text_size[ 1] + 2 + baseline) * i]
  52. img = draw_text(img, draw_point, text, drawType)
  53. return img
  54. if __name__ == "__main__":
  55. import copy
  56. image_path = "./data/test/test01.jpg"
  57. image = cv2.imread(image_path)
  58. point = ( 10, 10)
  59. text_line = "AAAA\nBBBB\nCCCC\n"
  60. image1 = draw_text(copy.copy(image), point, text_line, drawType= "custom")
  61. cv2.imshow( "draw_text", image1)
  62. image2 = draw_text_line(copy.copy(image), point, text_line)
  63. cv2.imshow( "draw_text_line", image2)
  64. cv2.waitKey( 0)
  65. cv2.waitKey( 0)

 


转载:https://blog.csdn.net/guyuealian/article/details/103498851
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场