# AUTOGENERATED! DO NOT EDIT! File to edit: ../../nbs/10e_bbox.vis.ipynb.

# %% auto 0
__all__ = ['overlay', 'overlay_label', 'overlay_bbox_labelled']

# %% ../../nbs/10e_bbox.vis.ipynb 4
from fastcore.all import *
import PIL
import numpy as np
import polvo as pv
from typing import Tuple
from PIL import Image, ImageFont
from PIL.ImageDraw import ImageDraw
from . import BBox, OBBox, BBoxLabeled, OBBoxLabeled

# %% ../../nbs/10e_bbox.vis.ipynb 5
def _random_color(): return tuple(((np.random.random(3)*0.6 + 0.4)*255).astype(int))

# %% ../../nbs/10e_bbox.vis.ipynb 6
def overlay(image:PIL.Image, bbox:BBox, color:Tuple[int,int,int]=None):
    """Draws a box on an image with a given color.
    # Arguments
        image     : The image to draw on.
        box       : A list of 4 elements (x1, y1, x2, y2).
        color     : The color of the box.
    """
    draw = PIL.ImageDraw.Draw(image)
    color = color or _random_color()
    bbox_thickness = int(0.0081*min(image.size) - 0.0078)
    bbox_thickness = np.clip(bbox_thickness, 1, 16)
    
    for i in range(4): draw.line(xy=(tuple(bbox.points[i]), tuple(bbox.points[(i+1)%4])), fill=color, width=bbox_thickness)
    return image

# %% ../../nbs/10e_bbox.vis.ipynb 10
def _default_font(scale=1.0):
    return ImageFont.truetype("DejaVuSans.ttf", size=int(10*scale))  # Generic sans-serif
#     except IOError: return ImageFont.load_default() 

# %% ../../nbs/10e_bbox.vis.ipynb 11
def overlay_label(image, label, x, y, color=None, text_scale=1.0, font=None, padding=0):
    color = color or _random_color()
#     font = font or ImageFont.load_default()
    font = font or _default_font(text_scale)
    draw = PIL.ImageDraw.Draw(image)
    # Calculate text size (try/except because font.getsize was deprecated in PIL)
    try:
        x1,y1, x2,y2 = font.getbbox(label)
        text_width, text_height = x2-x1, y2-y1
    except AttributeError:
        text_width, text_height = font.getsize(label)
        
    # Calculate box coordinates with padding
    if (y - text_height - padding) > 0:
        box_pt1, box_pt2 = (x, y+padding), (x+text_width+padding, y-text_height-padding)
        label_pt = (box_pt1[0], box_pt1[1]-text_height)
    else:
        box_pt1, box_pt2 = (x, y+text_height+ padding*2), (x+text_width+padding, y+padding)
        label_pt = (box_pt1[0], box_pt1[1])

    draw.rectangle([box_pt1, box_pt2], fill=color)
    draw.text(label_pt, label, font=font, fill=(240, 240, 240))
    return image

# %% ../../nbs/10e_bbox.vis.ipynb 13
@delegates(overlay_label)
def overlay_bbox_labelled(image, bbox, color=None, **kwargs):
    color = color or _random_color()
    image = overlay(image, bbox, color=color)
    x,y = bbox.xyxyxyxy[0]
    return overlay_label(image, bbox.label.name, x,y, color=color, **kwargs)
