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