Face Detection & Age Gender & Expression & Recognition

Overview

FaceLib:

  • use for Detection, Facial Expression, Age & Gender Estimation and Recognition with PyTorch
  • this repository works with CPU and GPU(Cuda)

Installation

  • Clone and install with this command:
    • with pip and automatic installs everything all you need

      • pip install git+https://github.com/sajjjadayobi/FaceLib.git
    • or with cloning the repo and install required packages

      • git clone https://github.com/sajjjadayobi/FaceLib.git
  • you can see the required packages in requirements.txt

How to use:

  • the simplest way is at example_notebook.ipynb
  • for low-level usage check out the following sections
  • if you have an NVIDIA GPU don't change the device param if not use cpu

1. Face Detection: RetinaFace

  • you can use these backbone networks: Resnet50, mobilenet
    • default weights and model is mobilenet and it will be automatically download
  • for more details, you can see the documentation
  • The following example illustrates the ease of use of this package:
 from facelib import FaceDetector
 detector = FaceDetector()
 boxes, scores, landmarks = detector.detect_faces(image)
  • FaceDetection live on your webcam
   from facelib import WebcamFaceDetector
   detector = WebcamFaceDetector()
   detector.run()

WiderFace Validation Performance on a single scale When using Mobilenet for backbone

Style easy medium hard
Pytorch (same parameter with Mxnet) 88.67% 87.09% 80.99%
Pytorch (original image scale) 90.70% 88.16% 73.82%
Mxnet(original image scale) 89.58% 87.11% 69.12%

2. Face Alignment: Similar Transformation

  • always use detect_align it gives you better performance
  • you can use this module like this:
    • detect_align instead of detect_faces
 from facelib import FaceDetector
 detector = FaceDetector()
 faces, boxes, scores, landmarks = detector.detect_align(image)
  • for more details read detect_image function documentation
  • let's see a few examples
Original Aligned & Resized Original Aligned & Resized
image image image image

3. Age & Gender Estimation:

  • I used UTKFace DataSet for Age & Gender Estimation
    • default weights and model is ShufflenetFull and it will be automatically download
  • you can use this module like this:
   from facelib import FaceDetector, AgeGenderEstimator

   face_detector = FaceDetector()
   age_gender_detector = AgeGenderEstimator()

   faces, boxes, scores, landmarks = face_detector.detect_align(image)
   genders, ages = age_gender_detector.detect(faces)
   print(genders, ages)
  • AgeGenderEstimation live on your webcam
   from facelib import WebcamAgeGenderEstimator
   estimator = WebcamAgeGenderEstimator()
   estimator.run()

4. Facial Expression Recognition:

  • Facial Expression Recognition using Residual Masking Network
    • default weights and model is densnet121 and it will be automatically download
  • face size must be (224, 224), you can fix it in FaceDetector init function with face_size=(224, 224)
  from facelib import FaceDetector, EmotionDetector
 
  face_detector = FaceDetector(face_size=(224, 224))
  emotion_detector = EmotionDetector()

  faces, boxes, scores, landmarks = face_detector.detect_align(image)
  list_of_emotions, probab = emotion_detector.detect_emotion(faces)
  print(list_of_emotions)
  • EmotionDetector live on your webcam
   from facelib import WebcamEmotionDetector
   detector = WebcamEmotionDetector()
   detector.run()
  • on my Webcam 🙂

Alt Text

5. Face Recognition: InsightFace

  • This module is a reimplementation of Arcface(paper), or Insightface(Github)

Pretrained Models & Performance

  • IR-SE50
LFW(%) CFP-FF(%) CFP-FP(%) AgeDB-30(%) calfw(%) cplfw(%) vgg2_fp(%)
0.9952 0.9962 0.9504 0.9622 0.9557 0.9107 0.9386
  • Mobilefacenet
LFW(%) CFP-FF(%) CFP-FP(%) AgeDB-30(%) calfw(%) cplfw(%) vgg2_fp(%)
0.9918 0.9891 0.8986 0.9347 0.9402 0.866 0.9100

Prepare the Facebank (For testing over camera, video or image)

  • the faces images you want to detect it save them in this folder:

    Insightface/models/data/facebank/
              ---> person_1/
                  ---> img_1.jpg
                  ---> img_2.jpg
              ---> person_2/
                  ---> img_1.jpg
                  ---> img_2.jpg
    
  • you can save a new preson in facebank with 3 ways:

    • use add_from_webcam: it takes 4 images and saves them on facebank
       from facelib import add_from_webcam
       add_from_webcam(person_name='sajjad')
    • use add_from_folder: it takes a path with some images from just a person
       from facelib import add_from_folder
       add_from_folder(folder_path='./', person_name='sajjad')
    • or add faces manually (just face of a person not image of a person)
      • I don't suggest this

Using

  • default weights and model is mobilenet and it will be automatically download
    import cv2
    from facelib import FaceRecognizer, FaceDetector
    from facelib import update_facebank, load_facebank, special_draw, get_config
 
    conf = get_config()
    detector = FaceDetector()
    face_rec = FaceRecognizer(conf)
    face_rec.model.eval()
    
    # set True when you add someone new 
    update_facebank_for_add_new_person = False
    if update_facebank_for_add_new_person:
        targets, names = update_facebank(conf, face_rec.model, detector)
    else:
        targets, names = load_facebank(conf)

    image = cv2.imread(your_path)
    faces, boxes, scores, landmarks = detector.detect_align(image)
    results, score = face_rec.infer(conf, faces, targets)
    print(names[results.cpu()])
    for idx, bbox in enumerate(boxes):
        special_draw(image, bbox, landmarks[idx], names[results[idx]+1], score[idx])
  • Face Recognition live on your webcam
   from facelib import WebcamVerify
   verifier = WebcamVerify(update=True)
   verifier.run()
  • example of run this code:

image

Reference:

Comments
  • pred = torch.argmax(input[:, :2], dim=1)

    pred = torch.argmax(input[:, :2], dim=1)

    In model.py:

    def accuracy_gender(input, targs): pred = torch.argmax(input[:, :2], dim=1) y = targs[:, 0] return torch.sum(pred == y)

    I want to know why not pred = input[:,:1] ? I think first two columns of input are genders and races.

    opened by Note-Liu 7
  • some questions

    some questions

    Hi , thanks your great job on this open project. there are some questions I confused , please give some clues on them:

    1. which sub dataset is used for training, the original wild or cropped? anyone is viable?
    2. why dont you use MoibleNet but ShuffleNet in Age and gender model? appreciate your effort again!
    opened by JH-Lam 6
  • Error in insightface

    Error in insightface

    I have created a dataset as data/facebank and kept the images inside individual person name. I am facing an error for the below mentioned block of code:

    if update_facebank_for_add_new_person: targets,names = update_facebank(conf, face_rec.model, detector) else: targets, names = load_facebank(conf)

    NameError Traceback (most recent call last) in () ----> 1 if update_facebank_for_add_new_person: 2 targets,names = update_facebank(conf, face_rec.model, detector) 3 else: 4 targets, names = load_facebank(conf)

    NameError: name 'update_facebank_for_add_new_person' is not defined

    opened by Rukhmini 6
  • How to Compare two faces?

    How to Compare two faces?

    Hello, Thank you for your great work Is there any way to compare two detected faces and return a percentage of similarity? In other words, is there any way to get face encodings ?

    opened by Adeel-Intizar 4
  • TypeError: infer() got multiple values for argument 'tta'

    TypeError: infer() got multiple values for argument 'tta'

    I captured an image using the add_from_webcam function and stored it in a facebank folder with the specified person_name as a directory.

    
    # from facelib import add_from_webcam
    
    # add_from_webcam(person_name='chuks')
    

    Now when I tried to verify the image in the folder using the WebcamVerify function.,It resulted to a TypeError. How can I fix this.?

    from facelib import WebcamVerify
    verifier = WebcamVerify(update=True)
    verifier.run()
    

    Error Traceback

    "C:\Users\Desktop\FaceRec\Project\FaceLib\facelib\InsightFace\verifier.py", line 49, in run
        results, score = self.recognizer.infer(self.conf, faces, self.targets, tta=self.tta)
    TypeError: infer() got multiple values for argument 'tta'
    
    opened by okoliechykwuka 3
  • RuntimeError: number of dims don't match in permute

    RuntimeError: number of dims don't match in permute

    When i try recognize same images, i get next error:

    Traceback (most recent call last): Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/uvicorn/protocols/http/h11_impl.py", line 396, in run_asgi result = await app(self.scope, self.receive, self.send) File "/usr/local/lib/python3.8/site-packages/uvicorn/middleware/proxy_headers.py", line 45, in call return await self.app(scope, receive, send) File "/usr/local/lib/python3.8/site-packages/fastapi/applications.py", line 199, in call await super().call(scope, receive, send) File "/usr/local/lib/python3.8/site-packages/starlette/applications.py", line 111, in call await self.middleware_stack(scope, receive, send) File "/usr/local/lib/python3.8/site-packages/starlette/middleware/errors.py", line 181, in call raise exc from None File "/usr/local/lib/python3.8/site-packages/starlette/middleware/errors.py", line 159, in call await self.app(scope, receive, _send) File "/usr/local/lib/python3.8/site-packages/starlette/middleware/cors.py", line 86, in call await self.simple_response(scope, receive, send, request_headers=headers) File "/usr/local/lib/python3.8/site-packages/starlette/middleware/cors.py", line 142, in simple_response await self.app(scope, receive, send) File "/usr/local/lib/python3.8/site-packages/starlette/exceptions.py", line 82, in call raise exc from None File "/usr/local/lib/python3.8/site-packages/starlette/exceptions.py", line 71, in call await self.app(scope, receive, sender) File "/usr/local/lib/python3.8/site-packages/starlette/routing.py", line 566, in call await route.handle(scope, receive, send) File "/usr/local/lib/python3.8/site-packages/starlette/routing.py", line 227, in handle await self.app(scope, receive, send) File "/usr/local/lib/python3.8/site-packages/starlette/routing.py", line 41, in app response = await func(request) File "/usr/local/lib/python3.8/site-packages/fastapi/routing.py", line 201, in app raw_response = await run_endpoint_function( File "/usr/local/lib/python3.8/site-packages/fastapi/routing.py", line 148, in run_endpoint_function return await dependant.call(**values) File "/app/./main.py", line 519, in get_age genders, ages = age_gender_detector.detect(faces) File "/usr/local/lib/python3.8/site-packages/facelib/AgeGender/Detector.py", line 46, in detect faces = faces.permute(0, 3, 1, 2) RuntimeError: number of dims don't match in permute

    Image sample: https://drive.google.com/open?id=14xAAW5a74dpNynF3xji5eMQO7yWjPN2c

    opened by vmorshc 3
  • pip install?

    pip install?

    I tried: pip install git+https://github.com/sajjjadayobi/FaceLib.git and also: python -m pip install git+https://github.com/sajjjadayobi/FaceLib.git Both did not work... it is kinda vague on the readme... I did install this before but I can´t remember how I did it Thanks

    opened by badjano 3
  • Issue with EasyDict

    Issue with EasyDict

    Hi, your requirements say EasyDict > 1.7.0 is required. I have 1.10.0 installed and get the following error:

    File "C:\Users\admin\anaconda3\envs\myproj\lib\site-packages\facelib\InsightFace\models\utils.py", line 11, in faces_preprocessing faces = faces.permute(0, 3, 1, 2).float() AttributeError: 'EasyDict' object has no attribute 'permute'

    Do you have any idea if the function has been renamed?

    opened by padmalcom 2
  • FaceLib on Nvidia Jetson Nano

    FaceLib on Nvidia Jetson Nano

    I have tried to install on Nvidia Jetson Nano. It support bcolz 1.2.0 and matplotlib 2.1.1. Could you share the oldest version of FaceLib that support older version of package ( bcolz 1.2.0 and matplotlib 2.1.1) ?

    opened by dspinczyk 2
  • ShuffleneTiny model for Age-Gender estimation

    ShuffleneTiny model for Age-Gender estimation

    Could you provide ShuffleneTiny model for Age-Gender estimation ? or guide how to preapare it ? I looked at TreB1eN / InsightFace_Pytorch and the model for mobile devices: Mobilefacenet - but as I understand it is not the same?

    opened by dspinczyk 2
  • could not run resnet model

    could not run resnet model

    Thanks for your great work, it runs mobilenet well but when I changed it to resnet the following Error incurred, Please kindly help.

    RuntimeError: Error(s) in loading state_dict for RetinaFace:
    	Missing key(s) in state_dict: "body.conv1.weight", "body.bn1.weight", "body.bn1.bias", "body.bn1.running_mean", "body.bn1.running_var", "body.layer1.0.conv1.weight", "body.layer1.0.bn1.weight", "body.layer1.0.bn1.bias", "body.layer1.0.bn1.running_mean", "body.layer1.0.bn1.running_var", "body.layer1.0.conv2.weight", "body.layer1.0.bn2.weight", "body.layer1.0.bn2.bias", "body.layer1.0.bn2.running_mean", "body.layer1.0.bn2.running_var", "body.layer1.0.conv3.weight", "body.layer1.0.bn3.weight", "body.layer1.0.bn3.bias", "body.layer1.0.bn3.running_mean", "body.layer1.0.bn3.running_var", "body.layer1.0.downsample.0.weight", "body.layer1.0.downsample.1.weight", "body.layer1.0.downsample.1.bias", "body.layer1.0.downsample.1.running_mean", "body.layer1.0.downsample.1.running_var", "body.layer1.1.conv1.weight", "body.layer1.1.bn1.weight", "body.layer1.1.bn1.bias", "body.layer1.1.bn1.running_mean", "body.layer1.1.bn1.running_var", "body.layer1.1.conv2.weight", "body.layer1.1.bn2.weight", "body.layer1.1.bn2.bias", "body.layer1.1.bn2.running_mean", "body.layer1.1.bn2.running_var", "body.layer1.1.conv3.weight", "body.layer1.1.bn3.weight", "body.layer1.1.bn3.bias", "body.layer1.1.bn3.running_mean", "body.layer1.1.bn3.running_var", "body.layer1.2.conv1.weight", "body.layer1.2.bn1.weight", "body.layer1.2.bn1.bias", "body.layer1.2.bn1.running_mean", "body.layer1.2.bn1.running_var", "body.layer1.2.conv2.weight", "body.layer1.2.bn2.weight", "body.layer1.2.bn2.bias", "body.layer1.2.bn2.runnin...
    	Unexpected key(s) in state_dict: "module.body.conv1.weight", "module.body.bn1.weight", "module.body.bn1.bias", "module.body.bn1.running_mean", "module.body.bn1.running_var", "module.body.bn1.num_batches_tracked", "module.body.layer1.0.conv1.weight", "module.body.layer1.0.bn1.weight", "module.body.layer1.0.bn1.bias", "module.body.layer1.0.bn1.running_mean", "module.body.layer1.0.bn1.running_var", "module.body.layer1.0.bn1.num_batches_tracked", "module.body.layer1.0.conv2.weight", "module.body.layer1.0.bn2.weight", "module.body.layer1.0.bn2.bias", "module.body.layer1.0.bn2.running_mean", "module.body.layer1.0.bn2.running_var", "module.body.layer1.0.bn2.num_batches_tracked", "module.body.layer1.0.conv3.weight", "module.body.layer1.0.bn3.weight", "module.body.layer1.0.bn3.bias", "module.body.layer1.0.bn3.running_mean", "module.body.layer1.0.bn3.running_var", "module.body.layer1.0.bn3.num_batches_tracked", "module.body.layer1.0.downsample.0.weight", "module.body.layer1.0.downsample.1.weight", "module.body.layer1.0.downsample.1.bias", "module.body.layer1.0.downsample.1.running_mean", "module.body.layer1.0.downsample.1.running_var", "module.body.layer1.0.downsample.1.num_batches_tracked", "module.body.layer1.1.conv1.weight", "module.body.layer1.1.bn1.weight", "module.body.layer1.1.bn1.bias", "module.body.layer1.1.bn1.running_mean", "module.body.layer1.1.bn1.running_var", "module.body.layer1.1.bn1.num_batches_tracked", "module.body.layer1.1.conv2.weight", "module.body.layer1.1.bn...
    
    opened by pengKiina 2
  • OpenCV gives an error after a few seconds of opening the window

    OpenCV gives an error after a few seconds of opening the window

    I wanted to try FaceLib with the emotion detector from my webcam, but I got an error after a few seconds when a frame opens!

    Code (from the README file):

    from facelib import WebcamEmotionDetector
    
    detector = WebcamEmotionDetector()
    detector.run()
    

    Error message:

    loading ...
    from EmotionDetector: weights loaded
    type q for exit
    Traceback (most recent call last):
      File "/home/sheikhartin/w/.tmp/facelib_demo.py", line 15, in <module>
        detector.run()
      File "/home/sheikhartin/.local/lib/python3.10/site-packages/facelib/FacialExpression/from_camera.py", line 27, in run
        special_draw(frame, b, landmarks[i], name=emotions[i], score=emo_probs[i])
      File "/home/sheikhartin/.local/lib/python3.10/site-packages/facelib/InsightFace/models/utils.py", line 117, in special_draw
        cv2.rectangle(img, c1, c2, color, thickness=tl)
    cv2.error: OpenCV(4.6.0) :-1: error: (-5:Bad argument) in function 'rectangle'
    > Overload resolution failed:
    >  - Can't parse 'pt1'. Sequence item with index 0 has a wrong type
    >  - Can't parse 'pt1'. Sequence item with index 0 has a wrong type
    >  - argument for rectangle() given by name ('thickness') and position (4)
    >  - argument for rectangle() given by name ('thickness') and position (4)
    
    opened by sheikhartin 0
Owner
Sajjad Ayobi
Data Science Lover, a Little Geek
Sajjad Ayobi
Deepface is a lightweight face recognition and facial attribute analysis (age, gender, emotion and race) framework for python

deepface Deepface is a lightweight face recognition and facial attribute analysis (age, gender, emotion and race) framework for python. It is a hybrid

Kushal Shingote 2 Feb 10, 2022
Implement face detection, and age and gender classification, and emotion classification.

YOLO Keras Face Detection Implement Face detection, and Age and Gender Classification, and Emotion Classification. (image from wider face dataset) Ove

Chloe 10 Nov 14, 2022
Age and Gender prediction using Keras

cnn_age_gender Age and Gender prediction using Keras Dataset example : Description : UTKFace dataset is a large-scale face dataset with long age span

XN3UR0N 58 May 3, 2022
This is an easy python software which allows to sort images with faces by gender and after by age.

Gender-age Classifier This is an easy python software which allows to sort images with faces by gender and after by age. Usage First install Deepface

Claudio Ciccarone 6 Sep 17, 2022
This is a Keras implementation of a CNN for estimating age, gender and mask from a camera.

face-detector-age-gender This is a Keras implementation of a CNN for estimating age, gender and mask from a camera. Before run face detector app, expr

Devdreamsolution 2 Dec 4, 2021
A deep learning network built with TensorFlow and Keras to classify gender and estimate age.

Convolutional Neural Network (CNN). This repository contains a source code of a deep learning network built with TensorFlow and Keras to classify gend

Pawel Dziemiach 1 Dec 18, 2021
A deep learning network built with TensorFlow and Keras to classify gender and estimate age.

Convolutional Neural Network (CNN). This repository contains a source code of a deep learning network built with TensorFlow and Keras to classify gend

Pawel Dziemiach 1 Dec 19, 2021
Face-Recognition-Attendence-System - This face recognition Attendence system using Python

Face-Recognition-Attendence-System I have developed this face recognition Attend

Riya Gupta 4 May 10, 2022
Face Library is an open source package for accurate and real-time face detection and recognition

Face Library Face Library is an open source package for accurate and real-time face detection and recognition. The package is built over OpenCV and us

null 52 Nov 9, 2022
Official repository of the paper Learning to Regress 3D Face Shape and Expression from an Image without 3D Supervision

Official repository of the paper Learning to Regress 3D Face Shape and Expression from an Image without 3D Supervision

Soubhik Sanyal 689 Dec 25, 2022
Spontaneous Facial Micro Expression Recognition using 3D Spatio-Temporal Convolutional Neural Networks

Spontaneous Facial Micro Expression Recognition using 3D Spatio-Temporal Convolutional Neural Networks Abstract Facial expression recognition in video

Bogireddy Sai Prasanna Teja Reddy 103 Dec 29, 2022
Official implementation for ICDAR 2021 paper "Handwritten Mathematical Expression Recognition with Bidirectionally Trained Transformer"

Handwritten Mathematical Expression Recognition with Bidirectionally Trained Transformer Description Convert offline handwritten mathematical expressi

Wenqi Zhao 87 Dec 27, 2022
Relative Uncertainty Learning for Facial Expression Recognition

Relative Uncertainty Learning for Facial Expression Recognition The official implementation of the following paper at NeurIPS2021: Title: Relative Unc

null 35 Dec 28, 2022
Software for Multimodalty 2D+3D Facial Expression Recognition (FER) UI

EmotionUI Software for Multimodalty 2D+3D Facial Expression Recognition (FER) UI. demo screenshot (with RealSense) required packages Python >= 3.6 num

Yang Jiao 2 Dec 23, 2021
Realtime micro-expression recognition using OpenCV and PyTorch

Micro-expression Recognition Realtime micro-expression recognition from scratch using OpenCV and PyTorch Try it out with a webcam or video using the e

Irfan 35 Dec 5, 2022
DVG-Face: Dual Variational Generation for Heterogeneous Face Recognition, TPAMI 2021

DVG-Face: Dual Variational Generation for HFR This repo is a PyTorch implementation of DVG-Face: Dual Variational Generation for Heterogeneous Face Re

null 52 Dec 30, 2022
A large-scale face dataset for face parsing, recognition, generation and editing.

CelebAMask-HQ [Paper] [Demo] CelebAMask-HQ is a large-scale face image dataset that has 30,000 high-resolution face images selected from the CelebA da

switchnorm 1.7k Dec 26, 2022
Facial detection, landmark tracking and expression transfer library for Windows, Linux and Mac

Welcome to the CSIRO Face Analysis SDK. Documentation for the SDK can be found in doc/documentation.html. All code in this SDK is provided according t

Luiz Carlos Vieira 7 Jul 16, 2020
Facial Expression Detection In The Realtime

The human's facial expressions is very important to detect thier emotions and sentiment. It can be very efficient to use to make our computers make interviews. Furthermore, we have robots now can detect the human's emotions and based on thats take an action .etc. So, It will be better to provide a tool or model for this.

Adel El-Nabarawy 4 Mar 1, 2022