# -*- coding: utf-8 -*-
"""minor2.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1actLRdpDfBgRyQ0yYrgH7LWB-CoU3O3w
"""

import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import cv2
import os
from PIL import Image
from keras.models import Sequential
from keras.layers import Input,Convolution2D,MaxPool2D,Flatten,Dense,Dropout,Convolution3D,MaxPool3D
from keras.utils import np_utils
import tensorflow
from keras.layers.convolutional import Conv3D
from keras.layers.convolutional_recurrent import ConvLSTM2D
from keras.layers.normalization import BatchNormalization
from keras.callbacks import ModelCheckpoint, EarlyStopping

def drawImage(img, title = "image"):
  imarray = np.array(img)
  plt.title(title+str(imarray.shape))
  plt.imshow(img)
  plt.show()

from google.colab import drive
drive.mount('/content/drive')

dirname = './DataSet/'
timeaccord= []
for fname in os.listdir(dirname):
  timeaccord.append(fname)
timeaccord.sort()

final = []
for fname in timeaccord[:24]:
    img = Image.open(os.path.join(dirname, fname))
    img = img.resize((100,100))
    drawImage(img,fname)
    imarray = np.array(img)
    final.append(imarray)

final = np.array(final)
final = final/255
print(final.shape)
x_train = []
y_train = []
for i in range(10,final.shape[0]):
  x_train.append(final[i-10:i])
for i in range(10,final.shape[0]):
  y_train.append(final[i-9:i+1])
  

X_train = np.array(x_train)
Y_train = np.array(y_train)
print(X_train.shape)
print(Y_train.shape)

seq = Sequential()
seq.add(ConvLSTM2D(filters=40, kernel_size=(3, 3),input_shape=(None, 100, 100, 1), padding='same', return_sequences=True))
seq.add(Dropout(0.1))
seq.add(BatchNormalization())

seq.add(ConvLSTM2D(filters=40, kernel_size=(3, 3), padding='same', return_sequences=True))
seq.add(Dropout(0.1))
seq.add(BatchNormalization())

seq.add(ConvLSTM2D(filters=40, kernel_size=(3, 3),padding='same', return_sequences=True))
seq.add(Dropout(0.1))
seq.add(BatchNormalization())

seq.add(ConvLSTM2D(filters=40, kernel_size=(3, 3),padding='same', return_sequences=True))
seq.add(Dropout(0.1))
seq.add(BatchNormalization())

seq.add(Conv3D(filters=1, kernel_size=(3, 3, 3),activation='sigmoid',padding='same', data_format='channels_last'))
seq.add(Dropout(0.1))

seq.summary()

seq.compile(loss='binary_crossentropy', optimizer='adadelta')

checkpoint = ModelCheckpoint("best_model.h5", monitor='val_loss', save_best_only=True, mode='auto', period=1)
early = EarlyStopping(monitor='val_acc', patience=2)
hist = seq.fit(X_train.reshape((14,10,100,100,1)), Y_train.reshape((14,10,100,100,1)), batch_size=10,
        epochs=32, validation_split=0.2,callbacks=[checkpoint,early])

#seq.load_weights("best_model.h5")

plt.figure(0)
plt.title("LOSS")
plt.plot(hist.history['loss'],'g')
plt.plot(hist.history['val_loss'],'b')
plt.show()

X_train = X_train.reshape((14,10,100,100,1))
which = 12
track = X_train[which][:10, ::, ::, ::]

for j in range(16):
    new_pos = seq.predict(track[np.newaxis, ::, ::, ::, ::])
    new = new_pos[::, -1, ::, ::, ::]
    track = np.concatenate((track, new), axis=0)


# And then compare the predictions
# to the ground truth
track2 = X_train[which][::, ::, ::, ::]
for i in range(15):
    fig = plt.figure(figsize=(10, 5))

    ax = fig.add_subplot(121)

    if i >= 10:
        ax.text(1, 3, 'Predictions !', fontsize=20, color='w')
    else:
        ax.text(1, 3, 'Initial trajectory', fontsize=20)

    toplot = track[i, ::, ::, 0]

    plt.imshow(toplot)
    ax = fig.add_subplot(122)
    plt.text(1, 3, 'Ground truth', fontsize=20)

    #toplot = track2[i, ::, ::, 0]
   # if i >= 2:
       # toplot = Y_train[which][i - 1,::, ::, 0]

    plt.imshow(toplot)
    plt.savefig('%i_animate.png' % (i + 1))

img = Image.open(os.path.join(dirname, timeaccord[25]))
img = img.resize((100,100))
plt.imshow(np.array(img)/9)

# -*- coding: utf-8 -*-
"""minor2.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1actLRdpDfBgRyQ0yYrgH7LWB-CoU3O3w
"""

import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import cv2
import os
from PIL import Image
from keras.models import Sequential
from keras.layers import Input,Convolution2D,MaxPool2D,Flatten,Dense,Dropout,Convolution3D,MaxPool3D
from keras.utils import np_utils
import tensorflow
from keras.layers.convolutional import Conv3D
from keras.layers.convolutional_recurrent import ConvLSTM2D
from keras.layers.normalization import BatchNormalization
from keras.callbacks import ModelCheckpoint, EarlyStopping

def drawImage(img, title = "image"):
  imarray = np.array(img)
  plt.title(title+str(imarray.shape))
  plt.imshow(img)
  plt.show()

from google.colab import drive
drive.mount('/content/drive')

dirname = './DataSet/'
timeaccord= []
for fname in os.listdir(dirname):
  timeaccord.append(fname)
timeaccord.sort()

final = []
for fname in timeaccord[:24]:
    img = Image.open(os.path.join(dirname, fname))
    img = img.resize((100,100))
    drawImage(img,fname)
    imarray = np.array(img)
    final.append(imarray)

final = np.array(final)
final = final/255
print(final.shape)
x_train = []
y_train = []
for i in range(10,final.shape[0]):
  x_train.append(final[i-10:i])
for i in range(10,final.shape[0]):
  y_train.append(final[i-9:i+1])
  

X_train = np.array(x_train)
Y_train = np.array(y_train)
print(X_train.shape)
print(Y_train.shape)

seq = Sequential()
seq.add(ConvLSTM2D(filters=40, kernel_size=(3, 3),input_shape=(None, 100, 100, 1), padding='same', return_sequences=True))
seq.add(Dropout(0.1))
seq.add(BatchNormalization())

seq.add(ConvLSTM2D(filters=40, kernel_size=(3, 3), padding='same', return_sequences=True))
seq.add(Dropout(0.1))
seq.add(BatchNormalization())

seq.add(ConvLSTM2D(filters=40, kernel_size=(3, 3),padding='same', return_sequences=True))
seq.add(Dropout(0.1))
seq.add(BatchNormalization())

seq.add(ConvLSTM2D(filters=40, kernel_size=(3, 3),padding='same', return_sequences=True))
seq.add(Dropout(0.1))
seq.add(BatchNormalization())

seq.add(Conv3D(filters=1, kernel_size=(3, 3, 3),activation='sigmoid',padding='same', data_format='channels_last'))
seq.add(Dropout(0.1))

seq.summary()

seq.compile(loss='binary_crossentropy', optimizer='adadelta')

checkpoint = ModelCheckpoint("best_model.h5", monitor='val_loss', save_best_only=True, mode='auto', period=1)
early = EarlyStopping(monitor='val_acc', patience=2)
hist = seq.fit(X_train.reshape((14,10,100,100,1)), Y_train.reshape((14,10,100,100,1)), batch_size=10,
        epochs=32, validation_split=0.2,callbacks=[checkpoint,early])

#seq.load_weights("best_model.h5")

plt.figure(0)
plt.title("LOSS")
plt.plot(hist.history['loss'],'g')
plt.plot(hist.history['val_loss'],'b')
plt.show()

X_train = X_train.reshape((14,10,100,100,1))
which = 12
track = X_train[which][:10, ::, ::, ::]

for j in range(16):
    new_pos = seq.predict(track[np.newaxis, ::, ::, ::, ::])
    new = new_pos[::, -1, ::, ::, ::]
    track = np.concatenate((track, new), axis=0)


# And then compare the predictions
# to the ground truth
track2 = X_train[which][::, ::, ::, ::]
for i in range(15):
    fig = plt.figure(figsize=(10, 5))

    ax = fig.add_subplot(121)

    if i >= 10:
        ax.text(1, 3, 'Predictions !', fontsize=20, color='w')
    else:
        ax.text(1, 3, 'Initial trajectory', fontsize=20)

    toplot = track[i, ::, ::, 0]

    plt.imshow(toplot)
    ax = fig.add_subplot(122)
    plt.text(1, 3, 'Ground truth', fontsize=20)

    #toplot = track2[i, ::, ::, 0]
   # if i >= 2:
       # toplot = Y_train[which][i - 1,::, ::, 0]

    plt.imshow(toplot)
    plt.savefig('%i_animate.png' % (i + 1))

img = Image.open(os.path.join(dirname, timeaccord[25]))
img = img.resize((100,100))
plt.imshow(np.array(img)/9)

# -*- coding: utf-8 -*- minor2.ipynb  Automatically generated by Colaboratory.  Original file is located at     https://colab.research.google.com/drive/1actLRdpDfBgRyQ0yYrgH7LWB-CoU3O3w #seq.load_weights("best_model.h5") # And then compare the predictions # to the ground truth #toplot = track2[i, ::, ::, 0] # if i >= 2: # toplot = Y_train[which][i - 1,::, ::, 0]