MCPcopy Create free account
hub / github.com/PyImageSearch/imutils / put_centered_text

Function put_centered_text

imutils/text.py:55–107  ·  view source on GitHub ↗

Utility for drawing vertically & horizontally centered text with line breaks :param img: Image. :param text: Text string to be drawn. :param font_face: Font type. One of FONT_HERSHEY_SIMPLEX, FONT_HERSHEY_PLAIN, FONT_HERSHEY_DUPLEX, FONT_HERSHEY_COMPLEX, FONT_H

(img, text, font_face, font_scale, color, thickness=1, line_type=8)

Source from the content-addressed store, hash-verified

53
54
55def put_centered_text(img, text, font_face, font_scale, color, thickness=1, line_type=8):
56 """Utility for drawing vertically & horizontally centered text with line breaks
57
58 :param img: Image.
59 :param text: Text string to be drawn.
60 :param font_face: Font type. One of FONT_HERSHEY_SIMPLEX, FONT_HERSHEY_PLAIN, FONT_HERSHEY_DUPLEX,
61 FONT_HERSHEY_COMPLEX, FONT_HERSHEY_TRIPLEX, FONT_HERSHEY_COMPLEX_SMALL,
62 FONT_HERSHEY_SCRIPT_SIMPLEX, or FONT_HERSHEY_SCRIPT_COMPLEX, where each of the font ID’s
63 can be combined with FONT_ITALIC to get the slanted letters.
64 :param font_scale: Font scale factor that is multiplied by the font-specific base size.
65 :param color: Text color.
66 :param thickness: Thickness of the lines used to draw a text.
67 :param line_type: Line type. See the line for details.
68 :return: None; image is modified in place
69 """
70 # Save img dimensions
71 img_h, img_w = img.shape[:2]
72
73 # Break text into list of text lines
74 text_lines = text.split('\n')
75
76 # Get height of text lines in pixels (height of all lines is the same; width differs)
77 _, line_height = cv2.getTextSize('', font_face, font_scale, thickness)[0]
78 # Set distance between lines in pixels
79 line_gap = line_height // 3
80
81 # Calculate total text block height for centering
82 text_block_height = len(text_lines) * (line_height + line_gap)
83 text_block_height -= line_gap # There's one less gap than lines
84
85 for i, text_line in enumerate(text_lines):
86 # Get width of text line in pixels (height of all lines is the same)
87 line_width, _ = cv2.getTextSize(text_line, font_face, font_scale, thickness)[0]
88
89 # Center line with image dimensions
90 x = (img_w - line_width) // 2
91 y = (img_h + line_height) // 2
92
93 # Find total size of text block before this line
94 line_adjustment = i * (line_gap + line_height)
95
96 # Adjust line y and re-center relative to total text block height
97 y += line_adjustment - text_block_height // 2 + line_gap
98
99 # Draw text
100 cv2.putText(img,
101 text=text_lines[i],
102 org=(x, y),
103 fontFace=font_face,
104 fontScale=font_scale,
105 color=color,
106 thickness=thickness,
107 lineType=line_type)

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…