from __future__ import print_function
import cv2
import numpy as np
import random
import copy
import os
# Load the Dataset of Stop Lights



from keras.datasets import cifar10
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.optimizers import SGD
from keras.utils import np_utils
from Load_Dataset import X_train,X_test,y_train,y_test
from keras.models import load_model

batch_size = 32
nb_classes = 3
nb_epoch = 1
data_augmentation = True

# input image dimensions
img_rows, img_cols = 32, 32
img_channels = 3



print(X_train.shape, 'X_train')
print(X_test.shape, 'X_test')
print(y_test.shape, 'y_test')
print(y_train.shape, 'y_train')

# convert class vectors to binary class matrices
Y_train = np_utils.to_categorical(y_train, nb_classes)
Y_test = np_utils.to_categorical(y_test, nb_classes)

model = Sequential()

model.add(Convolution2D(32, 3, 3, border_mode='same',
                        input_shape=(img_channels, img_rows, img_cols)))
model.add(Activation('relu'))
model.add(Convolution2D(32, 3, 3))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(Convolution2D(64, 3, 3, border_mode='same'))
model.add(Activation('relu'))
model.add(Convolution2D(64, 3, 3))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(Flatten())
model.add(Dense(512))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(nb_classes))
model.add(Activation('softmax'))

# let's train the model using SGD + momentum (how original).
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy',
              optimizer=sgd,
              metrics=['accuracy'])

X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255
X_test /= 255

if not data_augmentation:
    print('Not using data augmentation.')
    model.fit(X_train, Y_train,
              batch_size=batch_size,
              nb_epoch=nb_epoch,
              validation_data=(X_test, Y_test),
              shuffle=True)
else:
    print('Using real-time data augmentation.')

    # this will do preprocessing and realtime data augmentation
    datagen = ImageDataGenerator(
        featurewise_center=False,  # set input mean to 0 over the dataset
        samplewise_center=False,  # set each sample mean to 0
        featurewise_std_normalization=False,  # divide inputs by std of the dataset
        samplewise_std_normalization=False,  # divide each input by its std
        zca_whitening=False,  # apply ZCA whitening
        rotation_range=0,  # randomly rotate images in the range (degrees, 0 to 180)
        width_shift_range=0.1,  # randomly shift images horizontally (fraction of total width)
        height_shift_range=0.1,  # randomly shift images vertically (fraction of total height)
        horizontal_flip=True,  # randomly flip images
        vertical_flip=False)  # randomly flip images

    # compute quantities required for featurewise normalization
    # (std, mean, and principal components if ZCA whitening is applied)
    datagen.fit(X_train)

    # fit the model on the batches generated by datagen.flow()
    model.fit_generator(datagen.flow(X_train, Y_train,
                        batch_size=batch_size),
                        samples_per_epoch=X_train.shape[0],
                        nb_epoch=nb_epoch,
validation_data=(X_test, Y_test))

model.save('traffic_light.h5')
model.save_weights('traffic_light_weights.h5')


Images={}


f=open("Testing/frameAnnotationsBULB.csv",'r')
inputs=f.read()
f.close();

inputs=inputs.split()
inputs=[i.split(";") for i in inputs]
for i in range(21):
    inputs.pop(0)



for i in inputs:
    if i[1]=="stop":
        filename="Testing/frames/"+i[0][12:]
        print (filename)
        original_img=cv2.imread(filename)


        img=copy.copy(original_img)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
        
        b,g,r = cv2.split(img)
        clahe = cv2.createCLAHE(clipLimit=7.0, tileGridSize=(8,8)) # Adaptive histogram equilization
        clahe = clahe.apply(r)
        img = cv2.merge((b,g,clahe))
        
        # Threshold the HSV image to get only red colors
        img1 = cv2.inRange(img, np.array([0, 100, 100]), np.array([10,255,255]))
        img2 = cv2.inRange(img, np.array([160, 100, 100]), np.array([180,255,255]))
        img3 = cv2.inRange(img, np.array([160, 40, 60]), np.array([180,70,80]))
        img4 = cv2.inRange(img, np.array([0, 150, 40]), np.array([20,190,75]))
        img5 = cv2.inRange(img, np.array([145, 35, 65]), np.array([170,65,90]))
        

        img = cv2.bitwise_or(img1,img3)
        img = cv2.bitwise_or(img,img2)
        img = cv2.bitwise_or(img,img4)
        img = cv2.bitwise_or(img,img5)

        cv2.medianBlur(img,7)

        ret,thresh = cv2.threshold(img,127,255,0)
        contours, hierarchy = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)


        #size = (int(i[3]) - int(i[5]))*(int(i[2]) - int(i[4]))
        #window=int(0.1*size)
        #temp[int(i[3])-window: int(i[5])+window, int(i[2])-window: int(i[4])+window]=0

        for cnt in contours:
            area = cv2.contourArea(cnt)
            if area>20:
                pad=int(0.1*area)
                x,y,w,h = cv2.boundingRect(cnt)
                #cv2.rectangle(original_img, (x-pad,y-pad), (x+w+pad,y+h+pad),(255,0,0), 2)
                    
   
                try:
                    pad=int(0.1*w*h)
                    temp=original_img[y-pad:y+h+pad,x-pad:x+h+pad]
                    xx=cv2.resize(temp,(32,32))
                    xx=np.asarray(xx)
                    xx=np.transpose(xx,(2,0,1))
                    xx=np.reshape(xx,(1,3,32,32))
             
                    if model.predict_classes(xx,verbose=0)==[1]:
                        cv2.rectangle(original_img, (x-pad,y-pad), (x+w+pad,y+h+pad),(255,0,0), 2)
                    else:
                        cv2.rectangle(original_img, (x-pad,y-pad), (x+w+pad,y+h+pad),(0,0,255), 2)
        
                    cv2.imshow("Original",original_img)
       
                    cv2.waitKey(1)
                except:
                    pass

                


