[
  {
    "path": "FASNet.ipynb",
    "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"collapsed\": false\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"import os, time\\n\",\n    \"import h5py\\n\",\n    \"import numpy as np\\n\",\n    \"from keras.preprocessing.image import ImageDataGenerator,load_img,img_to_array\\n\",\n    \"from keras import optimizers\\n\",\n    \"from keras.models import Sequential\\n\",\n    \"from keras.layers import Convolution2D, MaxPooling2D, ZeroPadding2D\\n\",\n    \"from keras.layers import Activation, Dropout, Flatten, Dense\\n\",\n    \"from keras import callbacks\\n\",\n    \"from keras import backend as K\\n\",\n    \"\\n\",\n    \"K.set_image_dim_ordering('th')\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Train\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"collapsed\": true\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"# path to the model weights files.\\n\",\n    \"weights_path = ''\\n\",\n    \"top_model_weights_path = ''\\n\",\n    \"\\n\",\n    \"# dimensions of images. (less than 224x 224)\\n\",\n    \"img_width, img_height = (,)\\n\",\n    \"\\n\",\n    \"# nuumber of layers to freeze\\n\",\n    \"nFreeze = ()\\n\",\n    \"\\n\",\n    \"train_data_dir = ''\\n\",\n    \"validation_data_dir = ''\\n\",\n    \"nb_train_samples = ()\\n\",\n    \"nb_validation_samples = ()\\n\",\n    \"nb_epoch = ()\\n\",\n    \"\\n\",\n    \"def get_tr_vgg_model(weights_path, img_width, img_height):\\n\",\n    \"    \\n\",\n    \"    # build the VGG16 network\\n\",\n    \"    model = Sequential()\\n\",\n    \"    model.add(ZeroPadding2D((1, 1), input_shape=(3, img_width, img_height)))\\n\",\n    \"\\n\",\n    \"    model.add(Convolution2D(64, 3, 3, activation='relu', name='conv1_1'))\\n\",\n    \"    model.add(ZeroPadding2D((1, 1)))\\n\",\n    \"    model.add(Convolution2D(64, 3, 3, activation='relu', name='conv1_2'))\\n\",\n    \"    model.add(MaxPooling2D((2, 2), strides=(2, 2)))\\n\",\n    \"\\n\",\n    \"    model.add(ZeroPadding2D((1, 1)))\\n\",\n    \"    model.add(Convolution2D(128, 3, 3, activation='relu', name='conv2_1'))\\n\",\n    \"    model.add(ZeroPadding2D((1, 1)))\\n\",\n    \"    model.add(Convolution2D(128, 3, 3, activation='relu', name='conv2_2'))\\n\",\n    \"    model.add(MaxPooling2D((2, 2), strides=(2, 2)))\\n\",\n    \"\\n\",\n    \"    model.add(ZeroPadding2D((1, 1)))\\n\",\n    \"    model.add(Convolution2D(256, 3, 3, activation='relu', name='conv3_1'))\\n\",\n    \"    model.add(ZeroPadding2D((1, 1)))\\n\",\n    \"    model.add(Convolution2D(256, 3, 3, activation='relu', name='conv3_2'))\\n\",\n    \"    model.add(ZeroPadding2D((1, 1)))\\n\",\n    \"    model.add(Convolution2D(256, 3, 3, activation='relu', name='conv3_3'))\\n\",\n    \"    model.add(MaxPooling2D((2, 2), strides=(2, 2)))\\n\",\n    \"\\n\",\n    \"    model.add(ZeroPadding2D((1, 1)))\\n\",\n    \"    model.add(Convolution2D(512, 3, 3, activation='relu', name='conv4_1'))\\n\",\n    \"    model.add(ZeroPadding2D((1, 1)))\\n\",\n    \"    model.add(Convolution2D(512, 3, 3, activation='relu', name='conv4_2'))\\n\",\n    \"    model.add(ZeroPadding2D((1, 1)))\\n\",\n    \"    model.add(Convolution2D(512, 3, 3, activation='relu', name='conv4_3'))\\n\",\n    \"    model.add(MaxPooling2D((2, 2), strides=(2, 2)))\\n\",\n    \"\\n\",\n    \"    model.add(ZeroPadding2D((1, 1)))\\n\",\n    \"    model.add(Convolution2D(512, 3, 3, activation='relu', name='conv5_1'))\\n\",\n    \"    model.add(ZeroPadding2D((1, 1)))\\n\",\n    \"    model.add(Convolution2D(512, 3, 3, activation='relu', name='conv5_2'))\\n\",\n    \"    model.add(ZeroPadding2D((1, 1)))\\n\",\n    \"    model.add(Convolution2D(512, 3, 3, activation='relu', name='conv5_3'))\\n\",\n    \"    model.add(MaxPooling2D((2, 2), strides=(2, 2)))\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"    assert os.path.exists(weights_path), 'Model weights not found (see \\\"weights_path\\\" variable in script).'\\n\",\n    \"    f = h5py.File(weights_path)\\n\",\n    \"    for k in range(f.attrs['nb_layers']):\\n\",\n    \"        if k >= len(model.layers):\\n\",\n    \"            # we don't look at the last (fully-connected) layers in the savefile\\n\",\n    \"            break\\n\",\n    \"        g = f['layer_{}'.format(k)]\\n\",\n    \"        weights = [g['param_{}'.format(p)] for p in range(g.attrs['nb_params'])]\\n\",\n    \"        model.layers[k].set_weights(weights)\\n\",\n    \"    f.close()\\n\",\n    \"    print 'Model loaded.'\\n\",\n    \"    \\n\",\n    \"    return model\\n\",\n    \"\\n\",\n    \"def add_top_layers(model):\\n\",\n    \"\\n\",\n    \"    top_model = Sequential()\\n\",\n    \"    top_model.add(Flatten(input_shape=model.output_shape[1:]))\\n\",\n    \"    top_model.add(Dense(256, activation='relu'))\\n\",\n    \"    top_model.add(Dropout(0.5))\\n\",\n    \"    top_model.add(Dense(1, activation='sigmoid'))\\n\",\n    \"\\n\",\n    \"    # add the model on top of the convolutional base\\n\",\n    \"    model.add(top_model)\\n\",\n    \"    \\n\",\n    \"    return model\\n\",\n    \"\\n\",\n    \"def run_train(model):\\n\",\n    \"    \\n\",\n    \"    start_time = time.time()\\n\",\n    \"    \\n\",\n    \"    # freeze layers\\n\",\n    \"    for layer in model.layers[:nFreeze]:\\n\",\n    \"        layer.trainable = False\\n\",\n    \"\\n\",\n    \"    # compile model\\n\",\n    \"    model.compile(loss='binary_crossentropy',\\n\",\n    \"              optimizer=optimizers.Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=1e-6),\\n\",\n    \"              metrics=['accuracy'])\\n\",\n    \"    \\n\",\n    \"    print 'Model Compiled.'\\n\",\n    \"    \\n\",\n    \"    train_datagen = ImageDataGenerator(\\n\",\n    \"            rescale=1./255,\\n\",\n    \"            rotation_range=40,\\n\",\n    \"            width_shift_range=0.2,\\n\",\n    \"            height_shift_range=0.2,\\n\",\n    \"            shear_range=0.2,\\n\",\n    \"            zoom_range=0.2,\\n\",\n    \"            horizontal_flip=True,\\n\",\n    \"            vertical_flip = True,\\n\",\n    \"            fill_mode='nearest')\\n\",\n    \"\\n\",\n    \"    test_datagen = ImageDataGenerator(rescale=1./255)\\n\",\n    \"\\n\",\n    \"    train_generator = train_datagen.flow_from_directory(\\n\",\n    \"            train_data_dir,\\n\",\n    \"            target_size=(img_height, img_width),\\n\",\n    \"            batch_size=100,\\n\",\n    \"            class_mode='binary')\\n\",\n    \"\\n\",\n    \"    validation_generator = test_datagen.flow_from_directory(\\n\",\n    \"            validation_data_dir,\\n\",\n    \"            target_size=(img_height, img_width),\\n\",\n    \"            batch_size=100,\\n\",\n    \"            class_mode='binary')\\n\",\n    \"\\n\",\n    \"    print '\\\\nFine-tuning top layers...\\\\n'\\n\",\n    \"\\n\",\n    \"    earlyStopping = callbacks.EarlyStopping(monitor='val_acc',\\n\",\n    \"                                           patience=10, \\n\",\n    \"                                           verbose=0, mode='auto')\\n\",\n    \"\\n\",\n    \"    #fit model\\n\",\n    \"    model.fit_generator(\\n\",\n    \"           train_generator,\\n\",\n    \"           callbacks=[earlyStopping],\\n\",\n    \"           samples_per_epoch=nb_train_samples,\\n\",\n    \"           nb_epoch=nb_epoch,\\n\",\n    \"           validation_data=validation_generator,\\n\",\n    \"    nb_val_samples=nb_validation_samples)\\n\",\n    \"\\n\",\n    \"    model.save_weights(top_model_weights_path)\\n\",\n    \"    \\n\",\n    \"    print '\\\\nDone fine-tuning, have a nice day!'\\n\",\n    \"    print(\\\"\\\\nExecution time %s seconds\\\" % (time.time() - start_time))\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"collapsed\": false\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"if __name__ == \\\"__main__\\\":\\n\",\n    \"   \\n\",\n    \"    vgg16_tr_model = get_tr_vgg_model(weights_path, img_width, img_height)\\n\",\n    \"    vgg16_tr_model = add_top_layers(vgg16_tr_model)\\n\",\n    \"    \\n\",\n    \"    # fine-tuning the model \\n\",\n    \"    run_train(vgg16_tr_model)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Test\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"collapsed\": true\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"def load_model(weightsPath,img_width,img_height):\\n\",\n    \"    \\n\",\n    \"    #VGG-16 model\\n\",\n    \"    model = Sequential()\\n\",\n    \"   \\n\",\n    \"    model.add(ZeroPadding2D((1, 1), input_shape=(3, img_width, img_height)))\\n\",\n    \"    model.add(Convolution2D(64, 3, 3, activation='relu', name='conv1_1'))\\n\",\n    \"    model.add(ZeroPadding2D((1, 1)))\\n\",\n    \"    model.add(Convolution2D(64, 3, 3, activation='relu', name='conv1_2'))\\n\",\n    \"    model.add(MaxPooling2D((2, 2), strides=(2, 2)))\\n\",\n    \"\\n\",\n    \"    model.add(ZeroPadding2D((1, 1)))\\n\",\n    \"    model.add(Convolution2D(128, 3, 3, activation='relu', name='conv2_1'))\\n\",\n    \"    model.add(ZeroPadding2D((1, 1)))\\n\",\n    \"    model.add(Convolution2D(128, 3, 3, activation='relu', name='conv2_2'))\\n\",\n    \"    model.add(MaxPooling2D((2, 2), strides=(2, 2)))\\n\",\n    \"\\n\",\n    \"    model.add(ZeroPadding2D((1, 1)))\\n\",\n    \"    model.add(Convolution2D(256, 3, 3, activation='relu', name='conv3_1'))\\n\",\n    \"    model.add(ZeroPadding2D((1, 1)))\\n\",\n    \"    model.add(Convolution2D(256, 3, 3, activation='relu', name='conv3_2'))\\n\",\n    \"    model.add(ZeroPadding2D((1, 1)))\\n\",\n    \"    model.add(Convolution2D(256, 3, 3, activation='relu', name='conv3_3'))\\n\",\n    \"    model.add(MaxPooling2D((2, 2), strides=(2, 2)))\\n\",\n    \"\\n\",\n    \"    model.add(ZeroPadding2D((1, 1)))\\n\",\n    \"    model.add(Convolution2D(512, 3, 3, activation='relu', name='conv4_1'))\\n\",\n    \"    model.add(ZeroPadding2D((1, 1)))\\n\",\n    \"    model.add(Convolution2D(512, 3, 3, activation='relu', name='conv4_2'))\\n\",\n    \"    model.add(ZeroPadding2D((1, 1)))\\n\",\n    \"    model.add(Convolution2D(512, 3, 3, activation='relu', name='conv4_3'))\\n\",\n    \"    model.add(MaxPooling2D((2, 2), strides=(2, 2)))\\n\",\n    \"\\n\",\n    \"    model.add(ZeroPadding2D((1, 1)))\\n\",\n    \"    model.add(Convolution2D(512, 3, 3, activation='relu', name='conv5_1'))\\n\",\n    \"    model.add(ZeroPadding2D((1, 1)))\\n\",\n    \"    model.add(Convolution2D(512, 3, 3, activation='relu', name='conv5_2'))\\n\",\n    \"    model.add(ZeroPadding2D((1, 1)))\\n\",\n    \"    model.add(Convolution2D(512, 3, 3, activation='relu', name='conv5_3'))\\n\",\n    \"    model.add(MaxPooling2D((2, 2), strides=(2, 2)))\\n\",\n    \"    \\n\",\n    \"    # Top-model for anti-spoofing\\n\",\n    \"    top_model = Sequential()\\n\",\n    \"    top_model.add(Flatten(input_shape=model.output_shape[1:]))\\n\",\n    \"    top_model.add(Dense(256, activation='relu'))\\n\",\n    \"    top_model.add(Dropout(0.5))\\n\",\n    \"    top_model.add(Dense(1, activation='sigmoid'))\\n\",\n    \"    #\\n\",\n    \"    \\n\",\n    \"    model.add(top_model)\\n\",\n    \"    \\n\",\n    \"    if weightsPath:\\n\",\n    \"        model.load_weights(weightsPath)\\n\",\n    \"    else:\\n\",\n    \"        print 'Could not load model!'\\n\",\n    \"    \\n\",\n    \"    return model\\n\",\n    \"\\n\",\n    \"def read_preprocess_image(imgPath,img_width,img_height):\\n\",\n    \"      \\n\",\n    \"    img = load_img(imgPath,target_size=(img_width,img_height))\\n\",\n    \"    imgArray = img_to_array(img)\\n\",\n    \"    imgArray = imgArray.reshape(1,3,img_width, img_height)\\n\",\n    \"    imgArray = imgArray/float(255)\\n\",\n    \"    \\n\",\n    \"    return imgArray\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"collapsed\": false\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"if __name__ == \\\"__main__\\\":\\n\",\n    \"    \\n\",\n    \"    # load Parameters\\n\",\n    \"    imgPath = ''\\n\",\n    \"\\n\",\n    \"    img_width,img_height = (,)\\n\",\n    \"    \\n\",\n    \"    # read and Pre-processing image\\n\",\n    \"    img = read_preprocess_image(imgPath,img_width,img_height)\\n\",\n    \"\\n\",\n    \"    # load weights\\n\",\n    \"    model = load_model(top_model_weights_path,img_width,img_height)\\n\",\n    \"\\n\",\n    \"    # predict Class\\n\",\n    \"    opt = optimizers.Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=1e-6)\\n\",\n    \"    model.compile(loss='binary_crossentropy',\\n\",\n    \"              optimizer=opt,\\n\",\n    \"              metrics=['accuracy'])\\n\",\n    \"\\n\",\n    \"    outLabel = int(model.predict_classes(img,verbose=0))\\n\",\n    \"    print outLabel\\n\",\n    \"    \"\n   ]\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"Python 2\",\n   \"language\": \"python\",\n   \"name\": \"python2\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 2\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython2\",\n   \"version\": \"2.7.6\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 0\n}\n"
  },
  {
    "path": "LICENSE.txt",
    "content": "MIT License\n\nCopyright (c) 2017 OeslleLucena\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# FASNet\nThe face anti-spoofing network  (FASNet) is CNN archictecture based on Keras Example https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html\n\nVGG-16 weights: https://gist.github.com/baraldilorenzo/07d7802847aaad0a35d3\n\nPaper Accepted at 14th International Conference on\nImage Analysis and Recognition (ICIAR 2017): \"Transfer Learning Using Convolutional Neural Networks for Face Anti-Spoofing\".  \n\nPlease cite this work using information provided here: https://link.springer.com/chapter/10.1007%2F978-3-319-59876-5_4\n\n@Inbook{Lucena2017,\n  author=\"Lucena, Oeslle\n  and Junior, Amadeu\n  and Moia, Vitor\n  and Souza, Roberto\n  and Valle, Eduardo\n  and Lotufo, Roberto\",\n  editor=\"Karray, Fakhri\n  and Campilho, Aur{\\'e}lio\n  and Cheriet, Farida\",\n  title=\"Transfer Learning Using Convolutional Neural Networks for Face Anti-spoofing\",\n  bookTitle=\"Image Analysis and Recognition: 14th International Conference, ICIAR 2017, Montreal, QC, Canada, July 5--7, 2017,  Proceedings\",\n  year=\"2017\",\n  publisher=\"Springer International Publishing\",\n  address=\"Cham\",\n  pages=\"27--34\",\n  isbn=\"978-3-319-59876-5\",\n  doi=\"10.1007/978-3-319-59876-5_4\",\n  url=\"http://dx.doi.org/10.1007/978-3-319-59876-5_4\"\n}\n\n"
  }
]