Draw text on an image. Args: pos (tuple): x, y; the position of the text text (str): font_scale (float): color (tuple): a 3-tuple BGR color in [0, 255]
(img, pos, text, color, font_scale=0.4)
| 351 | |
| 352 | |
| 353 | def draw_text(img, pos, text, color, font_scale=0.4): |
| 354 | """ |
| 355 | Draw text on an image. |
| 356 | |
| 357 | Args: |
| 358 | pos (tuple): x, y; the position of the text |
| 359 | text (str): |
| 360 | font_scale (float): |
| 361 | color (tuple): a 3-tuple BGR color in [0, 255] |
| 362 | """ |
| 363 | img = img.astype(np.uint8) |
| 364 | x0, y0 = int(pos[0]), int(pos[1]) |
| 365 | # Compute text size. |
| 366 | font = cv2.FONT_HERSHEY_SIMPLEX |
| 367 | ((text_w, text_h), _) = cv2.getTextSize(text, font, font_scale, 1) |
| 368 | # Place text background. |
| 369 | if x0 + text_w > img.shape[1]: |
| 370 | x0 = img.shape[1] - text_w |
| 371 | if y0 - int(1.15 * text_h) < 0: |
| 372 | y0 = int(1.15 * text_h) |
| 373 | back_topleft = x0, y0 - int(1.3 * text_h) |
| 374 | back_bottomright = x0 + text_w, y0 |
| 375 | cv2.rectangle(img, back_topleft, back_bottomright, color, -1) |
| 376 | # Show text. |
| 377 | text_bottomleft = x0, y0 - int(0.25 * text_h) |
| 378 | cv2.putText(img, text, text_bottomleft, font, font_scale, (222, 222, 222), lineType=cv2.LINE_AA) |
| 379 | return img |
| 380 | |
| 381 | |
| 382 | def draw_boxes(im, boxes, labels=None, color=None): |