Exemplo n.º 1
0
 def _get_font(self):
     '''
     The function get size of font for image with given size
     :return: font for drawing
     '''
     return sly_font.get_font(
         font_size=sly_font.get_readable_font_size(self.img_size))
Exemplo n.º 2
0
def draw_text(bitmap: np.ndarray,
              text: str,
              anchor_point: tuple,
              corner_snap: CornerAnchorMode = CornerAnchorMode.TOP_LEFT,
              font: ImageFont.FreeTypeFont = None,
              fill_background=True) -> tuple:
    """
    Draws given text on bitmap image.
    Args:
        bitmap: target image (canvas)
        text: text for drawing
        anchor_point: start anchor point (row, column)
        corner_snap: control, how to draw text around `anchor_point`
        font: True-Type font object
        fill_background: draw background or not.

    Returns:
        Calculated (text_height, text_width) tuple. It may be helpful for some calculations
    """

    if font is None:
        font = get_font()

    source_img = PILImage.fromarray(bitmap)
    source_img = source_img.convert("RGBA")

    canvas = PILImage.new('RGBA', source_img.size, (0, 0, 0, 0))
    drawer = ImageDraw.Draw(canvas, "RGBA")
    text_width, text_height = drawer.textsize(text, font=font)
    rect_top, rect_left = anchor_point

    if corner_snap == CornerAnchorMode.TOP_LEFT:
        pass  # Do nothing
    elif corner_snap == CornerAnchorMode.TOP_RIGHT:
        rect_left -= text_width
    elif corner_snap == CornerAnchorMode.BOTTOM_LEFT:
        rect_top -= text_height
    elif corner_snap == CornerAnchorMode.BOTTOM_RIGHT:
        rect_top -= text_height
        rect_left -= text_width

    if fill_background:
        rect_right = rect_left + text_width
        rect_bottom = rect_top + text_height
        drawer.rectangle(
            ((rect_left, rect_top), (rect_right + 1, rect_bottom)),
            fill=(255, 255, 255, 128))
    drawer.text((rect_left + 1, rect_top),
                text,
                fill=(0, 0, 0, 255),
                font=font)

    source_img = PILImage.alpha_composite(source_img, canvas)
    source_img = source_img.convert("RGB")
    bitmap[:, :, :] = np.array(source_img, dtype=np.uint8)

    return (text_height, text_width)
Exemplo n.º 3
0
 def _get_font(self):
     return sly_font.get_font(
         font_size=sly_font.get_readable_font_size(self.img_size))