
import cv2
import numpy as np



watch_cascade = cv2.CascadeClassifier('./model/cascade_haar_tw2.xml')
#watch_cascade = cv2.CascadeClassifier('./model/cascade_lbp_tw4.xml')


def computeSafeRegion(shape,bounding_rect):
    top = bounding_rect[1] # y
    bottom  = bounding_rect[1] + bounding_rect[3] # y +  h
    left = bounding_rect[0] # x
    right =   bounding_rect[0] + bounding_rect[2] # x +  w

    min_top = 0
    max_bottom = shape[0]
    min_left = 0
    max_right = shape[1]

    # print "computeSateRegion input shape",shape
    if top < min_top:
        top = min_top
        # print "tap top 0"
    if left < min_left:
        left = min_left
        # print "tap left 0"

    if bottom > max_bottom:
        bottom = max_bottom
        #print "tap max_bottom max"
    if right > max_right:
        right = max_right
        #print "tap max_right max"

    # print "corr",left,top,right,bottom
    return [left,top,right-left,bottom-top]


def cropped_from_image(image,rect):
    x, y, w, h = computeSafeRegion(image.shape,rect)
    return image[y:y+h,x:x+w]


def detectPlateRough(image_gray,resize_h = 1000,en_scale =1.1 ,top_bottom_padding_rate = 0):
#    print(image_gray.shape)

#    if top_bottom_padding_rate>0.2:
#        print("error:top_bottom_padding_rate > 0.2:",top_bottom_padding_rate)
#        exit(1)

    height = image_gray.shape[0]
    padding =    int(height*top_bottom_padding_rate)
    scale = image_gray.shape[1]/float(image_gray.shape[0])

    image = cv2.resize(image_gray, (int(scale*resize_h), resize_h))

    image_color_cropped = image[padding:resize_h,0:image_gray.shape[1]]
#    image_color_cropped = image

    
    image_gray = cv2.cvtColor(image_color_cropped,cv2.COLOR_RGB2GRAY)
#    image_gray = cv2.bitwise_not(image_gray)
    watches = watch_cascade.detectMultiScale(image_gray, en_scale, 2, minSize=(31, 13),maxSize=(500,210))
    
        
    cropped_images = []
    for (x, y, w, h) in watches:
#       0329 測試擴增
#         y -= h * 0.1
#         h += h * 0.2;
        cropped_origin = cropped_from_image(image_color_cropped, (int(x), int(y), int(w), int(h)))
#        x -= w * 0.18
#        w += w * 0.36
#        縮減
#        x += w * 0.05
#        w -= w * 0.1;
        
#        correct
#         x -= w * 0.12
#         w += w * 0.24

#         cropped = cropped_from_image(image_color_cropped, (int(x), int(y), int(w), int(h)))
#         y -= h * 0.18
#         h += h * 0.36;
#         flagcrop = cropped_from_image(image_color_cropped, (int(x), int(y), int(w), int(h)))
     #        cropped = cropped_from_image(image_color_cropped, (int(x), int(y), int(w), int(h)))
        cropped=[]
        flagcrop=[]
        cropped_images.append([cropped,[x, y+padding, w, h],cropped_origin,flagcrop])
#        cropped_images.append([cropped,[x, y+padding, w, h],cropped_origin])
#        cropped_images.append([cropped, [x, y, w,h],cropped_origin])


    return cropped_images
