# AUTOGENERATED! DO NOT EDIT! File to edit: image-opencv_tools.ipynb (unless otherwise specified).

__all__ = ['limit_to_max_size', 'fit_to_max_size', 'get_image_size']


# Cell
import cv2


# Cell
def limit_to_max_size(img, max_size):
    """
    Limit the image size to max size and scale the image,
    if max size exceeded.
    `img`: The image to validate as OpenCV image.
    `max_size`: The max allowed image size.
    :return: The eventually resized opencv image.
    """
    biggest_size = max(img.shape[:2])
    if max_size and biggest_size > max_size:
        ratio = 1.0 * max_size / biggest_size
        img = cv2.resize(img, (int(ratio * img.shape[1]), int(ratio * img.shape[0])))
    return img


# Cell
def fit_to_max_size(img, max_width, max_height):
    """
    Limit the image size to maximum width and height and scale the image,
    if size exceeded.
    `img`: The image to validate as OpenCV Image.
    `max_width`: The max allowed image width.
    `max_height`: The max allowed image height.
    :return: The eventually resized OpenCV image.
    """
    h, w = img.shape[:2]
    scale_delta = max(w - max_width, h - max_height)
    if scale_delta > 0:
        max_size = max(w - scale_delta, h - scale_delta)
        img = limit_to_max_size(img, max_size)
    return img


# Cell
def get_image_size(fname):
    """
    Calculates image size of a given image file.
    `fname`: the file path
    return: the OpenCV image, image width and height
    """
    img = cv2.imread(fname)
    h, w = img.shape[:2]
    return img, w, h
