4
4
import math
5
5
import warnings
6
6
import numpy as np
7
- from PIL import Image , ImageDraw
8
- from PIL import ImageFont
7
+ from PIL import Image , ImageDraw , ImageFont , ImageColor
9
8
10
9
__all__ = ["make_grid" , "save_image" , "draw_bounding_boxes" ]
11
10
@@ -142,6 +141,7 @@ def draw_bounding_boxes(
142
141
boxes : torch .Tensor ,
143
142
labels : Optional [List [str ]] = None ,
144
143
colors : Optional [List [Union [str , Tuple [int , int , int ]]]] = None ,
144
+ fill : Optional [bool ] = False ,
145
145
width : int = 1 ,
146
146
font : Optional [str ] = None ,
147
147
font_size : int = 10
@@ -150,6 +150,7 @@ def draw_bounding_boxes(
150
150
"""
151
151
Draws bounding boxes on given image.
152
152
The values of the input image should be uint8 between 0 and 255.
153
+ If filled, Resulting Tensor should be saved as PNG image.
153
154
154
155
Args:
155
156
image (Tensor): Tensor of shape (C x H x W)
@@ -159,6 +160,7 @@ def draw_bounding_boxes(
159
160
labels (List[str]): List containing the labels of bounding boxes.
160
161
colors (List[Union[str, Tuple[int, int, int]]]): List containing the colors of bounding boxes. The colors can
161
162
be represented as `str` or `Tuple[int, int, int]`.
163
+ fill (bool): If `True` fills the bounding box with specified color.
162
164
width (int): Width of bounding box.
163
165
font (str): A filename containing a TrueType font. If the file is not found in this filename, the loader may
164
166
also search in other directories, such as the `fonts/` directory on Windows or `/Library/Fonts/`,
@@ -178,12 +180,31 @@ def draw_bounding_boxes(
178
180
179
181
img_boxes = boxes .to (torch .int64 ).tolist ()
180
182
181
- draw = ImageDraw .Draw (img_to_draw )
183
+ if fill :
184
+ draw = ImageDraw .Draw (img_to_draw , "RGBA" )
185
+
186
+ else :
187
+ draw = ImageDraw .Draw (img_to_draw )
188
+
182
189
txt_font = ImageFont .load_default () if font is None else ImageFont .truetype (font = font , size = font_size )
183
190
184
191
for i , bbox in enumerate (img_boxes ):
185
- color = None if colors is None else colors [i ]
186
- draw .rectangle (bbox , width = width , outline = color )
192
+ if colors is None :
193
+ color = None
194
+ else :
195
+ color = colors [i ]
196
+
197
+ if fill :
198
+ if color is None :
199
+ fill_color = (255 , 255 , 255 , 100 )
200
+ elif isinstance (color , str ):
201
+ # This will automatically raise Error if rgb cannot be parsed.
202
+ fill_color = ImageColor .getrgb (color ) + (100 ,)
203
+ elif isinstance (color , tuple ):
204
+ fill_color = color + (100 ,)
205
+ draw .rectangle (bbox , width = width , outline = color , fill = fill_color )
206
+ else :
207
+ draw .rectangle (bbox , width = width , outline = color )
187
208
188
209
if labels is not None :
189
210
draw .text ((bbox [0 ], bbox [1 ]), labels [i ], fill = color , font = txt_font )
0 commit comments