import numpy as np
import cv2 as cv


def normalize(images):
    images = np.clip(images, a_min=0.0, a_max=255.0)
    images = (images - 127.5) / 127.5
    return images

def denormalize(images):
    images = (images * 127.5) + 127.5
    images = np.clip(images, a_min=0.0, a_max=255.0)

    return images

def img2uint8(images):
    mn = images.min(axis=(-3, -2, -1), keepdims=True)
    mx = images.max(axis=(-3, -2, -1), keepdims=True)
    out = (images - mn) / mx
    out = (255.0 * out).astype('uint8')
    return out

def cv_read_image(path, is_bgr=True):
    img = cv.imread(path, cv.IMREAD_UNCHANGED)
    if is_bgr:
        img = cv.cvtColor(img, cv.COLOR_BGR2RGB)
    return img

def cv_process(img, img_size=None, channel_last=False, interpolation=cv.INTER_LINEAR):        
    if (img_size is not None) and (img.shape[:2] != img_size):
        img = cv.resize(img, img_size, interpolation=interpolation)
    if img.ndim == 2:
        img = img[..., None]
    if not channel_last:
        img = np.moveaxis(img, -1, 0)
    return img

def cv_rgb2gray(img):
    return cv.cvtColor(img, cv.COLOR_RGB2GRAY)

def apply_color_map(image, mask):
    heatmap = cv.resize(mask, image.shape[:2])
    heatmap = cv.normalize(heatmap, None, 0, 255, cv.NORM_MINMAX, cv.CV_8U)
    heatmap = cv.applyColorMap(heatmap, cv.COLORMAP_JET)
    heatmap = heatmap.astype(np.float32) / 255.0
    out = heatmap + image
    out = cv.normalize(out, None, 0, 255, cv.NORM_MINMAX, cv.CV_8U)
    return out

