#! /usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on 2022/5/6 11:06:36

@author: LiuKuan
@copyright: Apache License, Version 2.0
'''
# ===============================================================================
'''  
# Opencv  图像格式        通道：BGR 像素值：[0,255]        (h,w)
    gray是 (h,w)  
    color是(h,w,3)
    
cv2.INTER_LINEAR  = 1
'''
# ===============================================================================
__all__ = ['gray2bgr_cv', 'gray2rgb_cv',
           'bgr2gray_cv', 'rgb2gray_cv',
           'swap_rb_cv',
           'norm_uint8_cv', 'norm_float32_cv',
           'is_color_cv', 'is_gray_cv',
           'keep_bgr_cv', 'keep_gray_cv',
           'image_size_cv', 'resize_abs_cv', 'resize_rel_cv'
           ]

def gray2bgr_cv(img):
    import cv2
    if img.ndim == 2:
        img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
    return img

def gray2rgb_cv(img):
    import cv2
    if img.ndim == 2:
        img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
    return img

def bgr2gray_cv(img):
    import cv2
    if img.ndim == 3:
        if img.shape[-1] == 3:
            img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        elif img.shape[-1] == 4:
            img = cv2.cvtColor(img, cv2.COLOR_BGRA2GRAY)
    return img


def rgb2gray_cv(img):
    import cv2
    if img.ndim == 3:
        if img.shape[-1] == 3:
            img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
        elif img.shape[-1] == 4:
            img = cv2.cvtColor(img, cv2.COLOR_RGBA2GRAY)
    return img

def swap_rb_cv(img):
    import cv2
    if img.ndim == 3:
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    return img

def is_color_cv(img):
    return img.ndim == 3 and img.shape[-1] > 1

def is_gray_cv(img):
    return not is_color_cv(img)

def norm_uint8_cv(mat, alpha=0, beta=255):
    import cv2
    return cv2.normalize(mat, dst=None, alpha=alpha, beta=beta, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8U)

def norm_float32_cv(mat, alpha=0, beta=1):
    import cv2
    return cv2.normalize(mat, dst=None, alpha=alpha, beta=beta, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)

def norm_int32_cv(mat, alpha=0, beta=255):
    import cv2
    return cv2.normalize(mat, dst=None, alpha=alpha, beta=beta, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32S)

def keep_gray_cv(img):
    if is_color_cv(img):
        return bgr2gray_cv(img)
    return img

def keep_bgr_cv(img):
    if is_gray_cv(img):
        return gray2bgr_cv(img)
    return img

def image_size_cv(img):
    return (img.shape[1], img.shape[0])

def resize_abs_cv(img, width, height=0, interpolation=0):
    import cv2
    return cv2.resize(img, dsize=(int(width), int(height)), interpolation=interpolation)

def resize_rel_cv(img, fx=0.5, fy=0, interpolation=1):
    import cv2
    if fy == 0:
        fy = fx
    return cv2.resize(img, fx=fx, fy=fy, interpolation=interpolation)
