Skip to main content

A Lightweight Face Recognition and Facial Attribute Analysis Framework (Age, Gender, Emotion, Race) for Python

Project description

deepface

Downloads Stars License

Deepface is a lightweight face recognition and facial attribute analysis (age, gender, emotion and race) framework for python. It is a hybrid face recognition framework wrapping state-of-the-art models: VGG-Face, Google FaceNet, OpenFace, Facebook DeepFace, DeepID, ArcFace and Dlib. Those models already reached and passed the human level accuracy. The library is mainly based on Keras and TensorFlow.

Installation

The easiest way to install deepface is to download it from PyPI.

pip install deepface

Face Recognition

A modern face recognition pipeline consists of 4 common stages: detect, align, represent and verify. Deepface handles all these common stages in the background. You can just call its verification, find or analysis function in its interface with a single line of code.

Here, you can find an introduction video covering its functionalities and the best practices.

Face Verification - Demo

Verification function under the deepface interface offers to verify face pairs as same person or different persons.

from deepface import DeepFace
result  = DeepFace.verify("img1.jpg", "img2.jpg")

Herein, face pairs could be exact image paths, numpy array or base64 encoded images.

Face recognition - Demo

Face recognition requires to apply face verification several times. Herein, deepface offers an out-of-the-box find function to handle this action. It stores the representations of your facial database and you don't have to find it again and again. In this way, you can apply face recognition data set as well. The find function returns pandas data frame if a single image path is passed, and it returns list of pandas data frames if list of image paths are passed.

from deepface import DeepFace
df = DeepFace.find(img_path = "img1.jpg", db_path = "C:/workspace/my_db")

Herein, image path argument could be exact image path, numpy array or base64 encoded image. Also, you are expected to store your facial image data base in the folder that you passed to the db_path argument with .jpg or .png extension.

Face recognition models - Demo

Deepface is a hybrid face recognition package. It currently wraps the state-of-the-art face recognition models: VGG-Face , Google FaceNet, OpenFace, Facebook DeepFace, DeepID, ArcFace and Dlib. The default configuration verifies faces with VGG-Face model. You can set the base model while verification as illustared below.

models = ["VGG-Face", "Facenet", "OpenFace", "DeepFace", "DeepID", "ArcFace", "Dlib"]
result = DeepFace.verify("img1.jpg", "img2.jpg", model_name = models[1])
df = DeepFace.find(img_path = "img1.jpg", db_path = "C:/workspace/my_db", model_name = models[1])

FaceNet, VGG-Face, ArcFace and Dlib overperforms than OpenFace, DeepFace and DeepID based on experiments. Supportively, FaceNet got 99.65%; ArcFace got 99.40%; Dlib got 99.38%; VGG-Face got 98.78%; OpenFace got 93.80% accuracy scores on LFW data set whereas human beings could have just 97.53%.

Similarity

Face recognition models are regular convolutional neural networks and they are responsible to represent faces as vectors. Decision of verification is based on the distance between vectors. We can classify pairs if its distance is less than a threshold.

Distance could be found by different metrics such as Cosine Similarity, Euclidean Distance and L2 form. The default configuration finds the cosine similarity. You can alternatively set the similarity metric while verification as demostratred below.

metrics = ["cosine", "euclidean", "euclidean_l2"]
result = DeepFace.verify("img1.jpg", "img2.jpg", distance_metric = metrics[1])
df = DeepFace.find(img_path = "img1.jpg", db_path = "C:/workspace/my_db", distance_metric = metrics[1])

Euclidean L2 form seems to be more stable than cosine and regular Euclidean distance based on experiments.

Facial Attribute Analysis - Demo

Deepface also offers facial attribute analysis including age, gender, facial expression (including angry, fear, neutral, sad, disgust, happy and surprise) and race (including asian, white, middle eastern, indian, latino and black) predictions. Analysis function under the DeepFace interface is used to find demography of a face.

obj = DeepFace.analyze(img_path = "img4.jpg", actions = ['age', 'gender', 'race', 'emotion'])

Age model got ± 4.65 MAE; gender model got 97.44% accuracy, 96.29% precision and 95.05% recall as mentioned in its tutorial.

Herein, image path argument could be exact image path, numpy array or base64 encoded image.

Streaming and Real Time Analysis - Demo

You can run deepface for real time videos as well.

Calling stream function under the DeepFace interface will access your webcam and apply both face recognition and facial attribute analysis. Stream function expects a database folder including face images. VGG-Face is the default face recognition model and cosine similarity is the default distance metric similar to verify function. The function starts to analyze if it can focus a face sequantially 5 frames. Then, it shows results 5 seconds.

from deepface import DeepFace
DeepFace.stream("C:/User/Sefik/Desktop/database")

Even though face recognition is based on one-shot learning, you can use multiple face pictures of a person as well. You should rearrange your directory structure as illustrated below.

user
├── database
│   ├── Alice
│      ├── Alice1.jpg
│      ├── Alice2.jpg
│   ├── Bob
│      ├── Bob.jpg

Face Detectors - Demo

Face detection and alignment are early stages of a modern face recognition pipeline. OpenCV, SSD, Dlib, MTCNN and RetinaFace methods are wrapped in deepface as a facial detector. You can optionally pass a custom detector to functions in deepface interface. OpenCV is the default detector if you won't pass any detector.

backends = ['opencv', 'ssd', 'dlib', 'mtcnn', 'retinaface']

#face detection and alignment
detected_face = DeepFace.detectFace("img.jpg", detector_backend = backends[4])

#face verification
obj = DeepFace.verify("img1.jpg", "img2.jpg", detector_backend = backends[4])

#face recognition
df = DeepFace.find(img_path = "img.jpg", db_path = "my_db", detector_backend = backends[4])

#facial analysis
demography = DeepFace.analyze("img4.jpg", detector_backend = backends[4])

RetinaFace and MTCNN seem to overperform in detection and alignment stages but they are slower than others. If the speed of your pipeline is more important, then you should use opencv or ssd. On the other hand, if the accuracy is more important than the speed, then you should use retinaface or mtcnn.

Ensemble learning for face recognition - Demo

A face recognition task can be handled by several models and similarity metrics. Herein, deepface offers a special boosting and combination solution to improve the accuracy of a face recognition task. This provides a huge improvement on accuracy metrics. On the other hand, this runs much slower than single models.

resp_obj = DeepFace.verify("img1.jpg", "img2.jpg", model_name = "Ensemble")
df = DeepFace.find(img_path = "img1.jpg", db_path = "my_db", model_name = "Ensemble")

API - Demo

Deepface serves an API as well. You can clone /api/api.py and pass it to python command as an argument. This will get a rest service up. In this way, you can call deepface from an external system such as mobile app or web.

python api.py

The both face recognition and facial attribute analysis are covered in the API. You are expected to call these functions as http post methods. Service endpoints will be http://127.0.0.1:5000/verify for face recognition and http://127.0.0.1:5000/analyze for facial attribute analysis. You should pass input images as base64 encoded string in this case. Here, you can find a postman project.

Tech Stack - Vlog

The question is that where to store facial representations. You can find vector embeddings of facial images with the represent function.

embedding = DeepFace.represent("img.jpg", model_name = 'Facenet')

Recommended tech stack for face verification is mainly based on relational databases and regular SQL or key-value stores such as Redis or Cassandra. Herein, key-value stores overperform than regular relational databases.

Face verification is a subset of face recognition. In other words, you can run any face verification tool for face recognition as well. However, face verification has O(1) and face recognition has O(n) time complexity. That's why, face recognition becomes problematic with regular face verification tools on millions/billions level data and limited hardware.

You should use some big data solutions in face recognition when the data becomes huge. NoSQL databases comes with the power of map reduce technology. Here, Hadoop with Spark or Hive will overperform if you have lots of datanodes and clusters. Besides, mongoDb is a document database and it is highly scalable as well.

On the other hand, approximate nearest neighbor (a-nn) algorithm reduces the time complexity dramatically. Spotify Annoy, Facebook Faiss and NMSLIB are amazing a-nn libraries. Besides, Elasticsearch wraps an a-nn algorithm and it offers highly scalability feature. Moreover, Pinecone is fully cloud a-nn / k-nn solution. You should run deepface within those a-nn frameworks if you have really large scale data sets. Those libraries come with high speed but they don't guarantee to find the closest ones always in contrast to k-nn algorithm run in nosql databases.

Finally, graph databases offer to discover relations hard to find. Neo4j is a pretty graph database exploring indirect relations between facial images. If you plan to apply unsupervised learning and clustering, then graph databases will work well. It offers k-nn and a-nn algorithms as well.

Here, you can find some implementation demos of deepface with a-nn libraries: Elasticsearch and Spotify Annoy; key-value stores: Redis, Cassandra; and graph databases: Neo4j.

Contribution

Pull requests are welcome. You should run the unit tests locally by running test/unit_tests.py. Please share the unit test result logs in the PR. Deepface is currently compatible with TF 1 and 2 versions. Change requests should satisfy those requirements both.

Support

There are many ways to support a project - starring⭐️ the GitHub repos is just one.

Citation

Please cite deepface in your publications if it helps your research. Here is an example BibTeX entry:

@inproceedings{serengil2020lightface,
  title={LightFace: A Hybrid Deep Face Recognition Framework},
  author={Serengil, Sefik Ilkin and Ozpinar, Alper},
  booktitle={2020 Innovations in Intelligent Systems and Applications Conference (ASYU)},
  pages={23-27},
  year={2020},
  doi={10.1109/ASYU50717.2020.9259802},
  organization={IEEE}
}

Licence

Deepface is licensed under the MIT License - see LICENSE for more details. However, the library wraps some external face recognition models: VGG-Face, Facenet, OpenFace, DeepFace, DeepID, ArcFace and Dlib. Besides, age, gender and race / ethnicity models are based on VGG-Face. Licence types will be inherited if you are going to use those models.

Deepface logo is created by Adrien Coquet and it is licensed under Creative Commons: By Attribution 3.0 License.

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

deepface-0.0.63.tar.gz (57.7 kB view details)

Uploaded Source

Built Distribution

deepface-0.0.63-py3-none-any.whl (60.3 kB view details)

Uploaded Python 3

File details

Details for the file deepface-0.0.63.tar.gz.

File metadata

  • Download URL: deepface-0.0.63.tar.gz
  • Upload date:
  • Size: 57.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.1 importlib_metadata/3.10.0 pkginfo/1.7.0 requests/2.25.1 requests-toolbelt/0.9.1 tqdm/4.60.0 CPython/3.8.5

File hashes

Hashes for deepface-0.0.63.tar.gz
Algorithm Hash digest
SHA256 ce1714a833ba9877f15614ad84d21eeeb71485a8b1acc8a564a21740663bd55c
MD5 a38dfcc5adc05f40413c5ff9114518a2
BLAKE2b-256 d398b9e6971141d7416d709b4890744de3f6204efd57749607a52e29ff0ac31b

See more details on using hashes here.

File details

Details for the file deepface-0.0.63-py3-none-any.whl.

File metadata

  • Download URL: deepface-0.0.63-py3-none-any.whl
  • Upload date:
  • Size: 60.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.1 importlib_metadata/3.10.0 pkginfo/1.7.0 requests/2.25.1 requests-toolbelt/0.9.1 tqdm/4.60.0 CPython/3.8.5

File hashes

Hashes for deepface-0.0.63-py3-none-any.whl
Algorithm Hash digest
SHA256 6be35e7b4a75244859fd24648fb4dcb1ae66651684e5c3bf1519c8c22c86aef1
MD5 895d6a039015ca31df0637ac7bd04842
BLAKE2b-256 0523f138858cff8750c23a208c5b4e38f2225730628f59d83dc3ff15367001c8

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page