Given an image, pad the image at the top and add a title text. Note that the function converts image to uint8 Args: image: (*, h, w, 3) uint8 [0, 255] title: the str to add to the image font_size: font size to add font
(
image: np.ndarray,
title: str,
font_size: int = 24,
font_color: T.Union[float, T.List[float], None] = None, # [0, 1]
font_name: str = "DejaVuSans",
background_color: T.Union[float, T.List[float]] = 0., # [0, 1]
pad_height_px: int = 30,
align_width: str = 'center',
align_height: str = 'center',
)
| 559 | |
| 560 | |
| 561 | def add_title_to_image( |
| 562 | image: np.ndarray, |
| 563 | title: str, |
| 564 | font_size: int = 24, |
| 565 | font_color: T.Union[float, T.List[float], None] = None, # [0, 1] |
| 566 | font_name: str = "DejaVuSans", |
| 567 | background_color: T.Union[float, T.List[float]] = 0., # [0, 1] |
| 568 | pad_height_px: int = 30, |
| 569 | align_width: str = 'center', |
| 570 | align_height: str = 'center', |
| 571 | ) -> np.ndarray: |
| 572 | """ |
| 573 | Given an image, pad the image at the top and add a title text. |
| 574 | Note that the function converts image to uint8 |
| 575 | |
| 576 | Args: |
| 577 | image: |
| 578 | (*, h, w, 3) uint8 [0, 255] |
| 579 | title: |
| 580 | the str to add to the image |
| 581 | font_size: |
| 582 | font size to add |
| 583 | font_color: |
| 584 | font color of the text. If None, it will use the complement color of background_color. |
| 585 | font_name: |
| 586 | name of the font. |
| 587 | background_color: |
| 588 | background color |
| 589 | pad_height_px: |
| 590 | number of pixels to pad at the top of the image |
| 591 | align_width: |
| 592 | 'center', 'left', 'right' |
| 593 | align_height: |
| 594 | 'center', 'top', 'bottom' |
| 595 | |
| 596 | Returns: |
| 597 | the padded image: |
| 598 | (*, h+pad_height_px, w, 3) uint8 [0, 255] |
| 599 | """ |
| 600 | |
| 601 | if isinstance(background_color, (int, float)): |
| 602 | background_color = [background_color] * 3 |
| 603 | background_color = [int(c * 255) for c in background_color] |
| 604 | |
| 605 | if font_color is not None and isinstance(font_color, (int, float)): |
| 606 | font_color = [int(font_color * 255)] * 3 |
| 607 | if font_color is None: |
| 608 | font_color = [max(0, 255 - int(c)) for c in background_color] |
| 609 | |
| 610 | *b_shape, h, w, _c = image.shape |
| 611 | pad_region = np.ones((*b_shape, pad_height_px, w, 3), dtype=image.dtype) |
| 612 | for c in range(3): |
| 613 | pad_region[..., c] = background_color[c] |
| 614 | image = np.concatenate([pad_region, image], axis=-3) # (*b, h', w, 3) |
| 615 | |
| 616 | if title is None or len(title) == 0: |
| 617 | return image |
| 618 |