| 1 | import os.path as osp |
| 2 | |
| 3 | import matplotlib |
| 4 | import PIL.Image |
| 5 | import PIL.ImageDraw |
| 6 | import PIL.ImageFont |
| 7 | |
| 8 | from .. import utils |
| 9 | |
| 10 | |
| 11 | def _get_font(size, font_path=None): |
| 12 | if font_path is None: |
| 13 | fonts_path = osp.join(osp.dirname(matplotlib.__file__), "mpl-data/fonts/ttf") |
| 14 | font_path = osp.join(fonts_path, "DejaVuSansMono.ttf") |
| 15 | font = PIL.ImageFont.truetype(font=font_path, size=size) |
| 16 | return font |
| 17 | |
| 18 | |
| 19 | def text_size(text, size, font_path=None): |
| 20 | """Get text size (height and width). |
| 21 | |
| 22 | Parameters |
| 23 | ---------- |
| 24 | text: str |
| 25 | Text. |
| 26 | size: int |
| 27 | Pixel font size. |
| 28 | |
| 29 | Returns |
| 30 | ------- |
| 31 | height: int |
| 32 | Text height. |
| 33 | width: int |
| 34 | Text width. |
| 35 | |
| 36 | """ |
| 37 | font = _get_font(size, font_path=font_path) |
| 38 | |
| 39 | text_width = 0 |
| 40 | text_height = 0 |
| 41 | for line in text.splitlines(): |
| 42 | if line == "": |
| 43 | line = "\n" |
| 44 | |
| 45 | if hasattr(font, "getbbox"): |
| 46 | line_width, line_height = font.getbbox(line)[2:] |
| 47 | else: |
| 48 | line_width, line_height = font.getsize(line) |
| 49 | text_width = max(text_width, line_width) |
| 50 | text_height += line_height |
| 51 | |
| 52 | return text_height, text_width |
| 53 | |
| 54 | |
| 55 | def text(src, yx, text, size, color=(0, 0, 0), font_path=None): |
| 56 | """Draw text on numpy array with Pillow. |
| 57 | |
| 58 | Parameters |
| 59 | ---------- |
| 60 | src: numpy.ndarray |
| 61 | Input image. |
| 62 | yx: (2,) array-like |
| 63 | Left top point of the text. |
| 64 | text: str |
| 65 | Text to draw. |
| 66 | size: int |
| 67 | Text size in pixel. |
| 68 | color: (3,) array-like |
| 69 | Text RGB color in uint8. |
| 70 | Default is (0, 0, 0), which is black. |
| 71 | font_path: str |
| 72 | Default font is DejaVuSansMono in matplotlib. |
| 73 | |
| 74 | Returns |
| 75 | ------- |
| 76 | dst: numpy.ndarray |
| 77 | Output image. |
| 78 | |
| 79 | """ |
| 80 | dst = utils.numpy_to_pillow(src) |
| 81 | text_(img=dst, yx=yx, text=text, size=size, color=color, font_path=font_path) |
| 82 | return utils.pillow_to_numpy(dst) |
| 83 | |
| 84 | |
| 85 | def text_(img, yx, text, size, color=(0, 0, 0), font_path=None): |
| 86 | draw = PIL.ImageDraw.ImageDraw(img) |
| 87 | |
| 88 | y1, x1 = yx |
| 89 | color = tuple(color) |
| 90 | font = _get_font(size=size, font_path=font_path) |
| 91 | draw.text(xy=(x1, y1), text=text, fill=color, font=font) |