@@ -162,6 +162,7 @@ def draw_bounding_boxes(
162
162
font : Optional [str ] = None ,
163
163
font_size : Optional [int ] = None ,
164
164
label_colors : Optional [Union [List [Union [str , Tuple [int , int , int ]]], str , Tuple [int , int , int ]]] = None ,
165
+ fill_labels : bool = False ,
165
166
) -> torch .Tensor :
166
167
167
168
"""
@@ -186,7 +187,8 @@ def draw_bounding_boxes(
186
187
`/System/Library/Fonts/` and `~/Library/Fonts/` on macOS.
187
188
font_size (int): The requested font size in points.
188
189
label_colors (color or list of colors, optional): Colors for the label text. See the description of the
189
- `colors` argument for details. Defaults to the same colors used for the boxes.
190
+ `colors` argument for details. Defaults to the same colors used for the boxes, or to black if ``fill_labels`` is True.
191
+ fill_labels (bool): If `True` fills the label background with specified box color (from the ``colors`` parameter). Default: False.
190
192
191
193
Returns:
192
194
img (Tensor[C, H, W]): Image Tensor of dtype uint8 with bounding boxes plotted.
@@ -223,8 +225,8 @@ def draw_bounding_boxes(
223
225
)
224
226
225
227
colors = _parse_colors (colors , num_objects = num_boxes )
226
- if label_colors :
227
- label_colors = _parse_colors (label_colors , num_objects = num_boxes ) # type: ignore[assignment]
228
+ if label_colors or fill_labels :
229
+ label_colors = _parse_colors (label_colors if label_colors else "black" , num_objects = num_boxes ) # type: ignore[assignment]
228
230
else :
229
231
label_colors = colors .copy () # type: ignore[assignment]
230
232
@@ -259,7 +261,13 @@ def draw_bounding_boxes(
259
261
draw .rectangle (bbox , width = width , outline = color )
260
262
261
263
if label is not None :
262
- margin = width + 1
264
+ box_margin = 1
265
+ margin = width + box_margin
266
+ if fill_labels :
267
+ left , top , right , bottom = draw .textbbox ((bbox [0 ] + margin , bbox [1 ] + margin ), label , font = txt_font )
268
+ draw .rectangle (
269
+ (left - box_margin , top - box_margin , right + box_margin , bottom + box_margin ), fill = color
270
+ )
263
271
draw .text ((bbox [0 ] + margin , bbox [1 ] + margin ), label , fill = label_color , font = txt_font ) # type: ignore[arg-type]
264
272
265
273
out = F .pil_to_tensor (img_to_draw )
0 commit comments