import cv2
import numpy as np


def resize(image, size, interpolation=cv2.INTER_LINEAR):
    assert isinstance(image, np.ndarray)

    if isinstance(size, int):
        h, w = image.shape[:2]
        if (w <= h and w == size) or (h <= w and h == size):
            return image
        if w < h:
            ow = size
            oh = int(size * h / w)
            return cv2.resize(image, (ow, oh), interpolation=interpolation)
        else:
            oh = size
            ow = int(size * w / h)
            return cv2.resize(image, (ow, oh), interpolation=interpolation)
    else:
        return cv2.resize(image, tuple(size[::-1]), interpolation=interpolation)
    
# crop
def crop(image, y, x, h, w):
    assert isinstance(image, np.ndarray)
    return image[y:y+h, x:x+w]

# center crop
def center_crop(image, size):
    assert isinstance(image, np.ndarray)

    if isinstance(size, int):
        size = (int(size), int(size))

    h, w = image.shape[:2]
    oh, ow = size
    x = int(round((w - ow) / 2.))
    y = int(round((h - oh) / 2.))

    return crop(image, y, x, oh, ow)

def preprocess(img_file, need_batch=True):
    img = cv2.imread(img_file, cv2.IMREAD_COLOR)
    imgresize = resize(img, 256)
    imgcrop = center_crop(imgresize, 224)
    imgcrop = imgcrop.astype(np.float32)
    imgcrop = imgcrop - np.array([103.940002441, 116.779998779, 123.680000305], dtype=np.float32)
    imgcrop = imgcrop * np.array([0.0170000009239], dtype=np.float32)
    if need_batch:
        imgcrop = imgcrop[None, ...]
    return imgcrop
