# -*- coding: utf-8 -*-
"""
图像有关处理函数
@author: libo
"""
import os
import numpy as np
import cv2
from PIL import Image

def resize_im(w, h, scale=416, max_scale=608):
    f = float(scale) / min(h, w)
    if max_scale is not None:
        if f * max(h, w) > max_scale:
            f = float(max_scale) / max(h, w)
    newW, newH = int(w * f), int(h * f)
    return newW - (newW % 32), newH - (newH % 32)


def resize_image(img, pix_max, pix_min):
    img_size = img.shape
    h_mul_w = img_size[0] * img_size[1]

    im_scale = 1.0
    if h_mul_w > pix_max:
        im_scale = float(pix_max) / h_mul_w
    elif h_mul_w < pix_min:
        im_scale = float(pix_min) / h_mul_w

    new_h = int(img_size[0] * im_scale)
    new_w = int(img_size[1] * im_scale)
    # print('new_h = %d, new_w = %d' % (new_h, new_w))

    re_im = cv2.resize(img, (new_w, new_h), interpolation=cv2.INTER_LINEAR)
    return re_im, (float(new_h) / img_size[0], float(new_w) / img_size[1])


def solve(box):
    """ 结合 rotate_cut_img 函数实现对 img 的 roi 提取"""
    x1, y1, x2, y2, x3, y3, x4, y4 = box[:8]
    cx = (x1 + x3 + x2 + x4) / 4.0
    cy = (y1 + y3 + y4 + y2) / 4.0
    w = (np.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2) + np.sqrt((x3 - x4) ** 2 + (y3 - y4) ** 2)) / 2
    h = (np.sqrt((x2 - x3) ** 2 + (y2 - y3) ** 2) + np.sqrt((x1 - x4) ** 2 + (y1 - y4) ** 2)) / 2
    sinA = (h * (x1 - cx) - w * (y1 - cy)) * 1.0 / (h * h + w * w) * 2
    if abs(sinA) > 1:
        angle = None
    else:
        angle = np.arcsin(sinA)
    return angle, w, h, cx, cy


def rotate_cut_img(im, degree, box, w, h, leftAdjust=False, rightAdjust=False, alph=0.2):
    x1, y1, x2, y2, x3, y3, x4, y4 = box[:8]
    x_center, y_center = np.mean([x1, x2, x3, x4]), np.mean([y1, y2, y3, y4])
    degree_ = degree * 180.0 / np.pi
    right = 0
    left = 0
    if rightAdjust:
        right = 1
    if leftAdjust:
        left = 1

    box = (max(1, x_center - w / 2 - left * alph * (w / 2)),                    # xmin
           y_center - h / 2,                                                    # ymin
           min(x_center + w / 2 + right * alph * (w / 2), im.size[0] - 1),      # xmax
           y_center + h / 2)                                                    # ymax

    newW = box[2] - box[0]
    newH = box[3] - box[1]
    tmpImg = im.rotate(degree_, center=(x_center, y_center)).crop(box)
    return tmpImg, newW, newH