Skip to content

Commit acb2bbd

Browse files
authored
Add compatibility for custom font sizes on bounding boxes
As of PIL 10.1.0+ the `size` parameter is available in `PIL.ImageFont.load_default(size)`. This enables the `font_size` parameter in `draw_bounding_boxes` to be used even if `font=None`. See PIL docs: https://pillow.readthedocs.io/en/stable/reference/ImageFont.html#PIL.ImageFont.load_default
1 parent 947722a commit acb2bbd

File tree

1 file changed

+13
-3
lines changed

1 file changed

+13
-3
lines changed

torchvision/utils.py

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88

99
import numpy as np
1010
import torch
11+
12+
import PIL
1113
from PIL import Image, ImageColor, ImageDraw, ImageFont
1214

1315

@@ -184,7 +186,9 @@ def draw_bounding_boxes(
184186
font (str): A filename containing a TrueType font. If the file is not found in this filename, the loader may
185187
also search in other directories, such as the `fonts/` directory on Windows or `/Library/Fonts/`,
186188
`/System/Library/Fonts/` and `~/Library/Fonts/` on macOS.
187-
font_size (int): The requested font size in points.
189+
font_size (int): The requested font size in points. When using the default font (font=None),
190+
this parameter requires PIL version 10.1.0 or higher. For older PIL versions, the default
191+
font size will be used and a warning will be issued.
188192
label_colors (color or list of colors, optional): Colors for the label text. See the description of the
189193
`colors` argument for details. Defaults to the same colors used for the boxes.
190194
@@ -230,8 +234,14 @@ def draw_bounding_boxes(
230234

231235
if font is None:
232236
if font_size is not None:
233-
warnings.warn("Argument 'font_size' will be ignored since 'font' is not set.")
234-
txt_font = ImageFont.load_default()
237+
try:
238+
txt_font = ImageFont.load_default(size=font_size) # can set `size` parameter for default fonts as of PIL 10.1.0
239+
except TypeError:
240+
# Fallback for older PIL versions
241+
warnings.warn(f"The current version of PIL ({PIL.__version__}) does not support setting the `size` parameter for default font. PIL version 10.1.0+ required.")
242+
txt_font = ImageFont.load_default()
243+
else:
244+
txt_font = ImageFont.load_default()
235245
else:
236246
txt_font = ImageFont.truetype(font=font, size=font_size or 10)
237247

0 commit comments

Comments
 (0)