33import cv2
44import numpy as np
55from numpy .typing import NDArray
6+ from functools import lru_cache
67
78from ._utils import _check_and_modify_bbox , _validate_color
89
910font = cv2 .FONT_HERSHEY_SIMPLEX
1011
12+ # Cache text size calculations
13+ @lru_cache (maxsize = 128 )
14+ def _get_text_size (label : str , size : float , thickness : int ) -> tuple [tuple [int , int ], int ]:
15+ """Get text size with caching for better performance."""
16+ return cv2 .getTextSize (label , font , size , thickness )
17+
1118
1219def add_label (
1320 img : NDArray [np .uint8 ],
@@ -44,7 +51,8 @@ def add_label(
4451 _validate_color (text_color )
4552 bbox = _check_and_modify_bbox (bbox , img .shape )
4653
47- (text_width , text_height ), baseline = cv2 .getTextSize (label , font , size , thickness )
54+ # Use cached text size calculation
55+ (text_width , text_height ), baseline = _get_text_size (label , size , thickness )
4856 padding = 5 # Padding around text
4957
5058 if top and bbox [1 ] - text_height > text_height :
@@ -54,7 +62,7 @@ def add_label(
5462
5563 # Calculate background rectangle position
5664 bg_x1 = bbox [0 ]
57- bg_y1 = bbox [1 ] - bg_height # Removed the gap by removing (5 * size)
65+ bg_y1 = bbox [1 ] - bg_height
5866 bg_x2 = bg_x1 + bg_width
5967 bg_y2 = bg_y1 + bg_height
6068
@@ -127,7 +135,7 @@ def add_multiple_labels(
127135 text_color : tuple [int , int , int ] = (0 , 0 , 0 ),
128136 top : bool = True ,
129137) -> NDArray [np .uint8 ]:
130- """Add multiple labels to their corresponding bounding boxes.
138+ """Add multiple labels to their corresponding bounding boxes using optimized operations .
131139
132140 Args:
133141 img: Input image array
@@ -151,8 +159,25 @@ def add_multiple_labels(
151159
152160 _validate_color (text_bg_color )
153161 _validate_color (text_color )
162+
163+ # Convert bboxes to numpy array for vectorized operations
164+ bboxes = np .array (bboxes )
165+
166+ # Validate and modify all bboxes at once
167+ bboxes = np .array ([_check_and_modify_bbox (bbox , img .shape ) for bbox in bboxes ])
168+
169+ # Draw all labels using add_label
170+ output = img .copy ()
154171 for label , bbox in zip (labels , bboxes ):
155- img = add_label (
156- img , label , bbox , size , thickness , draw_bg , text_bg_color , text_color , top
172+ output = add_label (
173+ output ,
174+ label ,
175+ bbox .tolist (),
176+ size ,
177+ thickness ,
178+ draw_bg ,
179+ text_bg_color ,
180+ text_color ,
181+ top
157182 )
158- return img
183+ return output
0 commit comments