#AUTOGENERATED! DO NOT EDIT! File to edit: dev/00_utils.ipynb (unless otherwise specified).

__all__ = ['__all__', 'as_tensor', 'bgr2rgb', 'bgr2hsv', 'lapply', 'resize']

#Cell
import cv2
import numpy as np
import torch
from matplotlib.pyplot import imshow
from typing import Any, Union, Optional, Callable

#Cell
__all__ = ['as_tensor', 'resize',
           'bgr2rgb', 'bgr2hsv', 'lapply',
           'Any', 'Union', 'Optional', 'Callable',
           'np', 'torch', 'imshow', 'cv2']

#Cell
def as_tensor(image,
              dtype: Union[torch.FloatTensor, torch.HalfTensor, None]=torch.FloatTensor,
              normalise: bool = False) -> torch.Tensor:
    "Convert numpy array to torch tensor"
    x = torch.from_numpy(image)
    ## add x.names = ('H', 'W', 'C') once the names API is stable
    if dtype is not None: x = x.type(dtype)
    if normalise: x.div_(255)
    return x

#Cell
def bgr2rgb(x: np.ndarray) -> np.ndarray:
    """convert cv2 generated image array from BGR to RGB"""
    return cv2.cvtColor(x, cv2.COLOR_BGR2RGB)

#Cell
def bgr2hsv(x: np.ndarray) -> np.ndarray:
    """convert cv2 generated image array from BGR to HSV"""
    return cv2.cvtColor(x, cv2.COLOR_BGR2HSV)

#Cell
def lapply(x: Any, func: Callable) -> list:
    """Apply `func` to each element in list `x`"""
    return [func(i) for i in x]

#Cell

## SOURCE --> https://www.tutorialkart.com/opencv/python/opencv-python-resize-image/
def resize(image, height=None, width=None, keep_aspect_ratio=True, scale_factor=1.):
    """
    Resize by `scale_factor` if preserving aspect ratio else
    resize by custom `height` and `width`
    """
    h,w,_ = [*image.shape]
    if keep_aspect_ratio:
        assert scale_factor is not None, 'Enter `scale_factor`'
        assert width is None and height is None, '`height` and `width` must be ' +\
        'None if preserving aspect ratio. Use `scale_factor` instead'
        height = int(h * scale_factor)
        width  = int(w * scale_factor)
    else: assert height is not None and width is not None, 'Enter desired `height` and `width`'
    return cv2.resize(image, (width, height), cv2.INTER_AREA)