# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     name: python3
# ---

# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/connorj4/serial-multibiometric-face-fingerprint/blob/master/cnn_fingerprint.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>

# + id="nXRYFcKeeCLh" colab_type="code" outputId="72acabfd-1729-41d7-831c-323f719e57ad" colab={"base_uri": "https://localhost:8080/", "height": 34}
from google.colab import drive
drive.mount('/content/drive', force_remount=True)

gdrive_home_dir = '/content/drive/My Drive/'

# + id="g310W7Bcmqtp" colab_type="code" outputId="8c95e655-57cd-4099-8acc-a02e13bfca62" colab={"base_uri": "https://localhost:8080/", "height": 170}
# !ls '/content/drive/My Drive/dataset_fp/labelfinger.csv'
# !ls '/content/drive/My Drive/dataset_fp/data/'


# + id="tSHR-OA1c40N" colab_type="code" colab={}
from __future__ import print_function
import numpy as np

# + id="sS3_oeBJcoWP" colab_type="code" colab={}
np.random.seed(1337)  # for reproducibility

# + id="LyK02LtMcq6-" colab_type="code" outputId="13441e5f-a097-4522-b29c-f64ebfb3adb8" colab={"base_uri": "https://localhost:8080/", "height": 34}
import pandas as pd
from PIL import Image
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.utils import np_utils
from keras import backend as K

# + id="0T8w8xsKcpM7" colab_type="code" colab={}
batch_size = 10
nb_classes = 10
nb_epoch = 2


# + id="uDpUl8gycjD9" colab_type="code" colab={}
# To make the data ready for CNN, pictures are named with indexes, like '1.jpg', '2.jpg', etc..
def dir_to_dataset(mypath, loc_train_labels=""):
    dataset = []
    
    gbr = pd.read_csv(loc_train_labels, sep="\t")

    #for file_count, file_name in enumerate( sorted(glob(glob_files),key=len) ):
    for i in range(1,81):
        image = Image.open(mypath + str(i)+'.jpg')
        img = Image.open(mypath + str(i)+'.jpg').convert('LA') #tograyscale
        '''
        pixels_list = list(img.getdata())
        for pixel in pixels_list:
          p = pixel
          dataset.append(p)
        '''
        #pixels_list = list(img.getdata())
        #width, height = img.size
        #pixels = [pixels[i * width:(i + 1) * width] for i in range(height)]
        
        pixels = [f[0] for f in list(img.getdata())] #<- original
        dataset.append(pixels)
    # outfile = glob_files+"out"
    # np.save(outfile, dataset)
    if len(loc_train_labels) > 0:
        df = pd.read_csv(loc_train_labels)
        return np.array(dataset), gbr["Class"].values
    else:
        return np.array(dataset)


# + id="6ZglATaj7btE" colab_type="code" outputId="9cd4e7cf-afdf-4224-9f34-871a2f8583d6" colab={"base_uri": "https://localhost:8080/", "height": 802}
if __name__ == '__main__':
    Data, y = dir_to_dataset("/content/drive/My Drive/dataset_fp/data/","/content/drive/My Drive/dataset_fp/labelfinger.csv")
    
    #Split the train set and validation set
    train_set_x = Data[:60]
    val_set_x = Data[10:]
    train_set_y = y[:60]
    val_set_y = y[10:]

    (X_train, y_train), (X_test, y_test) = (train_set_x,train_set_y),(val_set_x,val_set_y)

    # input image dimensions
    img_rows, img_cols = 640, 480
    # number of convolutional filters to use
    nb_filters = 32
    # size of pooling area for max pooling
    pool_size = (2, 2)
    # convolution kernel size
    kernel_size = (3, 3)
    
    

    # Checking if the backend is Theano or Tensorflow
    if K.image_dim_ordering() == 'th':
        X_train = X_train.reshape(X_train.shape[0], 1, img_rows, img_cols)
        X_test = X_test.reshape(X_test.shape[0], 1, img_rows, img_cols)
        input_shape = (1, img_rows, img_cols)
    else:
        X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, 1)
        X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, 1)
        input_shape = (img_rows, img_cols, 1) 

    X_train = X_train.astype('float32')
    X_test = X_test.astype('float32')
    X_train /= 255
    X_test /= 255
    print('X_train shape:', X_train.shape)
    print(X_train.shape[0], 'train samples')
    print(X_test.shape[0], 'test samples')

    # 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(nb_filters, kernel_size[0], kernel_size[1],
                    border_mode='valid',
                    input_shape=input_shape))
    model.add(Activation('relu'))
    model.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1]))
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=pool_size))
    model.add(Dropout(0.25))

    model.add(Flatten())
    #model.add(Dense(128))
    model.add(Dense(32))
    model.add(Activation('relu'))
    model.add(Dropout(0.5))
    model.add(Dense(nb_classes))
    model.add(Activation('softmax'))

    model.compile(loss='categorical_crossentropy',
            optimizer='sgd',
            metrics=['accuracy'])

    model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=1, validation_data=(X_test, Y_test))
    score = model.evaluate(X_test, Y_test, verbose=0)
    
    print(model.summary())
    
    print('Test score:', score[0])
    print('Test accuracy:', score[1])
    
    

StarcoderdataJupyterScriptsDedupFiltered