diff --git a/ultralytics/utils/plotting.py b/ultralytics/utils/plotting.py index 569b0b7c..02bff920 100644 --- a/ultralytics/utils/plotting.py +++ b/ultralytics/utils/plotting.py @@ -290,14 +290,15 @@ class Annotator: if self.pil or not is_ascii(label): if rotated: p1 = box[0] - # NOTE: PIL-version polygon needs tuple type. - self.draw.polygon([tuple(b) for b in box], width=self.lw, outline=color) + self.draw.polygon([tuple(b) for b in box], width=self.lw, outline=color) # PIL requires tuple box else: p1 = (box[0], box[1]) self.draw.rectangle(box, width=self.lw, outline=color) # box if label: w, h = self.font.getsize(label) # text width, height - outside = p1[1] - h >= 0 # label fits outside box + outside = p1[1] >= h # label fits outside box + if p1[0] > self.im.size[1] - w: # check if label extend beyond right side of image + p1 = self.im.size[1] - w, p1[1] self.draw.rectangle( (p1[0], p1[1] - h if outside else p1[1], p1[0] + w + 1, p1[1] + 1 if outside else p1[1] + h + 1), fill=color, @@ -307,20 +308,22 @@ class Annotator: else: # cv2 if rotated: p1 = [int(b) for b in box[0]] - # NOTE: cv2-version polylines needs np.asarray type. - cv2.polylines(self.im, [np.asarray(box, dtype=int)], True, color, self.lw) + cv2.polylines(self.im, [np.asarray(box, dtype=int)], True, color, self.lw) # cv2 requires nparray box else: p1, p2 = (int(box[0]), int(box[1])), (int(box[2]), int(box[3])) cv2.rectangle(self.im, p1, p2, color, thickness=self.lw, lineType=cv2.LINE_AA) if label: w, h = cv2.getTextSize(label, 0, fontScale=self.sf, thickness=self.tf)[0] # text width, height - outside = p1[1] - h >= 3 - p2 = p1[0] + w, p1[1] - h - 3 if outside else p1[1] + h + 3 + h += 3 # add pixels to pad text + outside = p1[1] >= h # label fits outside box + if p1[0] > self.im.shape[1] - w: # check if label extend beyond right side of image + p1 = self.im.shape[1] - w, p1[1] + p2 = p1[0] + w, p1[1] - h if outside else p1[1] + h cv2.rectangle(self.im, p1, p2, color, -1, cv2.LINE_AA) # filled cv2.putText( self.im, label, - (p1[0], p1[1] - 2 if outside else p1[1] + h + 2), + (p1[0], p1[1] - 2 if outside else p1[1] + h - 1), 0, self.sf, txt_color, @@ -441,8 +444,9 @@ class Annotator: else: if box_style: w, h = cv2.getTextSize(text, 0, fontScale=self.sf, thickness=self.tf)[0] # text width, height - outside = xy[1] - h >= 3 - p2 = xy[0] + w, xy[1] - h - 3 if outside else xy[1] + h + 3 + h += 3 # add pixels to pad text + outside = xy[1] >= h # label fits outside box + p2 = xy[0] + w, xy[1] - h if outside else xy[1] + h cv2.rectangle(self.im, xy, p2, txt_color, -1, cv2.LINE_AA) # filled # Using `txt_color` for background and draw fg with white color txt_color = (255, 255, 255)