# @Author  : lightXu
# @File    : predict.py
import time

import cv2
import numpy as np

from segment.sheet_resolve.tools.tf_settings import decide_blank_model

model = np.load(decide_blank_model)


def round_float(value):
    return round(value, 6)


def gen_feature(img):
    h, w = img.shape
    mean = round_float(np.mean(img)/255)
    aspect = round_float(h / w)

    row_box, col_box = 4, 4
    row_box_pix, col_box_pix = h // row_box, w // col_box

    box_feature = [aspect, mean]
    for r in range(row_box):
        for c in range(col_box):
            box = img[r*row_box_pix:(r+1)*row_box_pix, c*col_box_pix:(c+1)*col_box_pix]
            box_mean = round_float(np.mean(box)/255)
            box_feature.append(box_mean)

    return box_feature


def kernel_trans(x1, array, k_tup=('rbf', 1.3)):
    if k_tup[0] == 'lin':
        kernel = np.dot(x1, array)
    elif k_tup[0] == 'rbf':
        sigma = k_tup[1]
        if np.ndim(x1) == 1:
            kernel = np.exp(np.sum(np.square(x1 - array)) / (-1 * np.square(sigma)))
        else:
            kernel = np.sum(np.square(x1-array), axis=1)
            kernel = np.exp(-kernel / np.square(sigma))
    else:
        raise NameError('核函数无法识别')

    return kernel


def svm_predict(img, subject_id=3):
    feature = gen_feature(img)
    feature.insert(0, subject_id)

    feature = np.array(feature, dtype=np.float)

    # model = np.load('model.npy')
    alpha_y = model[:, 0].T
    b = model[0, 1]
    sVs = model[:, 2:]

    fxk = np.dot(alpha_y, kernel_trans(sVs, feature)) + b
    p = np.sign(fxk)
    if p == 1:
        # print('blank')
        return True
    else:
        # print('unblank')
        return False


if __name__ == '__main__':
    file = r'E:\math_svm\test\202005060540_0001_214731356c.jpg'
    im = cv2.imread(file, 0)
    t1 = time.time()
    svm_predict(im)
    t2 = time.time()
    print(t2-t1)
