From 21df296425310df7f5c7541060c1daf717c98e94 Mon Sep 17 00:00:00 2001 From: Glenn Jocher Date: Sat, 17 Jun 2023 20:10:47 +0200 Subject: [PATCH] Fix PIL `getsize()` deprecation warning (#3234) Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- ultralytics/yolo/utils/plotting.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/ultralytics/yolo/utils/plotting.py b/ultralytics/yolo/utils/plotting.py index 12193d6..9061ca1 100644 --- a/ultralytics/yolo/utils/plotting.py +++ b/ultralytics/yolo/utils/plotting.py @@ -54,7 +54,6 @@ class Annotator: non_ascii = not is_ascii(example) # non-latin labels, i.e. asian, arabic, cyrillic self.pil = pil or non_ascii if self.pil: # use PIL - self.pil_9_2_0_check = check_version(pil_version, '9.2.0') # deprecation check self.im = im if isinstance(im, Image.Image) else Image.fromarray(im) self.draw = ImageDraw.Draw(self.im) try: @@ -63,6 +62,9 @@ class Annotator: self.font = ImageFont.truetype(str(font), size) except Exception: self.font = ImageFont.load_default() + # Deprecation fix for w, h = getsize(string) -> _, _, w, h = getbox(string) + if check_version(pil_version, '9.2.0'): + self.font.getsize = lambda x: self.font.getbbox(x)[2:4] # text width, height else: # use cv2 self.im = im self.lw = line_width or max(round(sum(im.shape) / 2 * 0.003), 2) # line width @@ -80,10 +82,7 @@ class Annotator: if self.pil or not is_ascii(label): self.draw.rectangle(box, width=self.lw, outline=color) # box if label: - if self.pil_9_2_0_check: - _, _, w, h = self.font.getbbox(label) # text width, height (New) - else: - w, h = self.font.getsize(label) # text width, height (Old, deprecated in 9.2.0) + w, h = self.font.getsize(label) # text width, height outside = box[1] - h >= 0 # label fits outside box self.draw.rectangle( (box[0], box[1] - h if outside else box[1], box[0] + w + 1,