55
66from __future__ import annotations
77
8- from PIL import Image , ImageDraw
8+ from PIL import Image , ImageDraw , ImageFont
9+
10+ from model_api .visualizer .defaults import DEFAULT_FONT_SIZE , DEFAULT_OUTLINE_WIDTH
911
1012from .primitive import Primitive
1113
@@ -20,6 +22,8 @@ class BoundingBox(Primitive):
2022 y2 (int): y-coordinate of the bottom-right corner of the bounding box.
2123 label (str | None): Label of the bounding box.
2224 color (str | tuple[int, int, int]): Color of the bounding box.
25+ outline_width (int): Width of the bounding box outline.
26+ font_size (int): Font size for the label text.
2327
2428 Example:
2529 >>> bounding_box = BoundingBox(x1=10, y1=10, x2=100, y2=100, label="Label Name")
@@ -34,30 +38,35 @@ def __init__(
3438 y2 : int ,
3539 label : str | None = None ,
3640 color : str | tuple [int , int , int ] = "blue" ,
41+ outline_width : int = DEFAULT_OUTLINE_WIDTH ,
42+ font_size : int = DEFAULT_FONT_SIZE ,
3743 ) -> None :
3844 self .x1 = x1
3945 self .y1 = y1
4046 self .x2 = x2
4147 self .y2 = y2
4248 self .label = label
4349 self .color = color
44- self .y_buffer = 5 # Text at the bottom of the text box is clipped. This prevents that.
50+ self .outline_width = outline_width
51+ self .font_size = font_size
52+ self .font = ImageFont .load_default (size = self .font_size )
53+ self .y_buffer = max (3 , font_size // 3 ) # Text at the bottom of the text box is clipped. This prevents that.
4554
4655 def compute (self , image : Image ) -> Image :
4756 draw = ImageDraw .Draw (image )
4857 # draw rectangle
49- draw .rectangle ((self .x1 , self .y1 , self .x2 , self .y2 ), outline = self .color , width = 2 )
58+ draw .rectangle ((self .x1 , self .y1 , self .x2 , self .y2 ), outline = self .color , width = self . outline_width )
5059 # add label
5160 if self .label :
5261 # draw the background of the label
53- textbox = draw .textbbox ((0 , 0 ), self .label )
62+ textbox = draw .textbbox ((0 , 0 ), self .label , font = self . font )
5463 label_image = Image .new (
5564 "RGB" ,
5665 (textbox [2 ] - textbox [0 ], textbox [3 ] + self .y_buffer - textbox [1 ]),
5766 self .color ,
5867 )
5968 draw = ImageDraw .Draw (label_image )
6069 # write the label on the background
61- draw .text ((0 , 0 ), self .label , fill = "white" )
70+ draw .text ((0 , 0 ), self .label , font = self . font , fill = "white" )
6271 image .paste (label_image , (self .x1 , self .y1 ))
6372 return image
0 commit comments