[ECCV 2020] Reimplementation of 3DDFAv2, including face mesh, head pose, landmarks, and more.

Overview

Stable Head Pose Estimation and Landmark Regression via 3D Dense Face Reconstruction

FaceReconstructionDemo

Language grade: Python License ECCV

Reimplementation of (ECCV 2020) Towards Fast, Accurate and Stable 3D Dense Face Alignment via Tensorflow Lite framework, face mesh, head pose, landmarks, and more.

  • CPU real-time face deteciton, alignment, and reconstruction pipeline.
  • Lightweight render library, 5x faster (3ms vs 15ms) than the Sim3DR tools.
  • Camera matrix and dense/sparse landmarks prediction via a single network.
  • Generate facial parameters for robust head pose and expression estimation.

Setup

Basic Requirements

  • Python 3.6+
  • pip3 install -r requirements.txt

Render for Dense Face

  • GCC 6.0+
  • bash build_render.sh
  • (Cautious) For Windows user, please refer to this tutorial for more details.

3D Facial Landmarks

In this project, we perform dense face reconstruction by 3DMM parameters regression. The regression target is simplified as camera matrix (C, shape of 3x4), appearance parameters (S, shape of 1x40), and expression variables (E, shape of 1x10), with 62 dimensions in total.

The sparse or dense facial landmarks can be estimated by applying these parameters to a predefined 3D model, such as BFM. More specifically, the following formula describes how to generate a face through parameters:

Generate Face

where U and W are from pre-defined face model. Combine them linearly with parameters to generate sparse or dense faces. Finally, we need to integrate the posture information into the result:

With matrix

where R (shape of 3x3) and T (shape of 3x1) denote rotation and translation matrices, respectively, which are fractured from the camera matrix C.

Sparse

sparse demo

Since we have reconstructed the entire face, the 3D face alignment can be achieved by selecting the landmarks at the corresponding positions. See [TPAMI 2017] Face alignment in full pose range: A 3d total solution for more details.

Comparing with the method of first detecting 2D landmarks and then performing depth estimation, directly fitting 3DMM to solve 3D face alignment can not only obtain more accurate results in larger pose scenes, but also has obvious advantages in speed.

We provide a demonstration script that can generate 68 landmarks based on the reconstructed face. Run the following command to view the real-time 3D face alignment results:

python3 demo_video.py -m sparse -f <your-video-path>

Dense

dense demo

Currently, our method supports up to 38,365 landmarks. We draw landmarks every 6 indexes for a better illustration. Run the demonstrate script in dense mode for real-time dense facial landmark localization:

python3 demo_video.py -m dense -f <your-video-path>

Face Reconstruction

Our network is multi-task since it can directly regress 3DMM params from a single face image for reconstruction, as well as estimate the head pose via R and T prediction. During training, the predicted R can supervise the params regression branch to generate refined face mesh. Meanwhile, the landmarks calculated via the params are provided as the labeled data to the pose estimation branch for training, through the cv2.solvePnP tool.

Theoretically speaking, the head pose estimation task in our model is weakly supervised, since only a few labeled data is required to activate the training process. In detail, the loss function at the initial stage can be described as follows:

Init Pose Loss

After the initialization process, the ground truth can be replaced by the prediction results of other branches. Therefore, the loss function will be transformed to the following equation in the later stage of the training process:

Pose Loss

In general, fitting the 3D model during the training process dynamically can avoid the inaccurate head pose estimation results caused by the coarse predefined model.

Head Pose

pose demo

Traditional head pose estimation approaches, such as Appearance Template Models, Detector Arrays, and Mainfold Embedding have been extensively studied. However, methods based on deep learning improved the prediction accuracy to meet actual needs, until recent years.

Given a set of predefined 3D facial landmarks and the corresponding 2D image projections, the SolvePnP tool can be utilized to calculate the rotation matrix. However, the adopted mean 3D human face model usually introduces intrinsic error during the fitting process. Meanwhile, the additional landmarks extraction component is also kind of cumbersome.

Therefore, we designed a network branch for directly regress 6DoF parameters from the face image. The predictions include the 3DoF rotation matrix R (Pitch, Yaw, Roll), and the 3DoF translation matrix T (x, y, z), Compared with the landmark-based method, directly regression the camera matrix is more robust and stable, as well as significantly reduce the network training cost. Run the demonstrate script in pose mode to view the real-time head pose estimation results:

python3 demo_video.py -m pose -f <your-video-path>

Expression

Expression

Coarse expression estimation can be achieved by combining the predefined expressions in BFM linearly. In our model, regression the E is one of the tasks of the params prediction branch. Obviously, the accuracy of the linear combination is positively related to the dimension.

Clipping parameters can accelerate the training process, however, it can also reduce reconstruction accuracy, especially details such as eye and mouth. More specifically, E has a greater impact on face details than S when emotion is involved. Therefore, we choose 10-dimension for a tradeoff between the speed and the accuracy, the training data can be found at here for refinement.

In addition, we provide a simple facial expression rendering script. Run the following command for illustration:

python3 demo_image.py <your-image-path>

Mesh

mesh demo

According to the predefined BFM and the predicted 3DMM parameters, the dense 3D facial landmarks can be easily calculated. On this basis, through the index mapping between the morphable triangle vertices and the dense landmarks defined in BFM, the renderer can plot these geometries with depth infomation for mesh preview. Run the demonstrate script in mesh mode for real-time face reconstruction:

python3 demo_video.py -m mesh -f <your-video-path>

Benchmark

Our network can directly output the camera matrix and sparse or dense landmarks. Compared with the model in the original paper with the same backbone, the additional parameters yield via the pose regression branch does not significantly affect the inference speed, which means it can still be CPU real-time.

Scheme THREAD=1 THREAD=2 THREAD=4
Inference 7.79ms 6.88ms 5.83ms

In addition, since most of the operations are wrapped in the model, the time consumption of pre-processing and post-processing are significantly reduced. Meanwhile, the optimized lightweight renderer is 5x faster (3ms vs 15ms) than the Sim3DR tools. These measures decline the latency of the entire pipeline.

Stage Preprocess Inference Postprocess Render
Each face cost 0.23ms 7.79ms 0.39ms 3.92ms

Run the following command for speed benchmark:

python3 video_speed_benchmark.py <your-video-path>

Citation

@inproceedings{guo2020towards,
    title={Towards Fast, Accurate and Stable 3D Dense Face Alignment},
    author={Guo, Jianzhu and Zhu, Xiangyu and Yang, Yang and Yang, Fan and Lei, Zhen and Li, Stan Z},
    booktitle={Proceedings of the European Conference on Computer Vision (ECCV)},
    year={2020}
}
Comments
  • __init__() got an unexpected keyword argument 'num_threads'

    __init__() got an unexpected keyword argument 'num_threads'

    While running "python3 demo_video.py -m mesh -f I receive the following ERROR: File "demo_video.py", line 53, in main(args) File "demo_video.py", line 16, in main fa = service.DenseFaceReconstruction("weights/dense_face.tflite") File "/home/happy/PycharmProjects/Dense-Head-Pose-Estimation/service/TFLiteFaceAlignment.py", line 11, in init num_threads=num_threads) TypeError: init() got an unexpected keyword argument 'num_threads'

    opened by berylyellow 2
  • asset/render.so not found

    asset/render.so not found

    While running "python3 demo_video.py -m mesh -f I receive the following ERROR OSError: asset/render.so: cannot open shared object file: No such file or directory I can successfully run the other three modes (sparse, dense, pose)

    opened by fisakhan 2
  • How can i get Depth

    How can i get Depth

    hi, I want to get information about the depth of the face, how do I calculate it? i don't need rendering but only need depth map. like https://github.kakaocorp.com/data-sci/3DDFA_V2_tf2/blob/master/utils/depth.py thank you in advance!

    opened by joongkyunKim 1
  • there is no asset/render.so

    there is no asset/render.so

    Ignore above cudart dlerror if you do not have a GPU set up on your machine. Traceback (most recent call last): File "demo_video.py", line 53, in main(args) File "demo_video.py", line 18, in main color = service.TrianglesMeshRender("asset/render.so", File "/home/xuhao/workspace/Dense-Head-Pose-Estimation-main/service/CtypesMeshRender.py", line 17, in init self._clibs = ctypes.CDLL(clibs)

    opened by hitxuhao 1
  • asset/render.so: cannot open shared object file: No such file or director

    asset/render.so: cannot open shared object file: No such file or director

    It worked well with: $ python3 demo_video.py -m pose -f ./re.mp4 $python3 demo_video.py -m sparse -f ./re.mp4 $ python3 demo_video.py -m dense -f ./re.mp4

    but with mesh not as you see here:

    $python3 demo_video.py -m mesh -f ./re.mp4 2022-12-05 17:03:03.713207: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcudart.so.10.1 Traceback (most recent call last): File "demo_video.py", line 55, in main(args) File "demo_video.py", line 21, in main color = service.TrianglesMeshRender("asset/render.so", "asset/triangles.npy") File "/home/redhwan/2/HPE/tensorflow/Dense-Head-Pose-Estimation-main/service/CtypesMeshRender.py", line 17, in init self._clibs = ctypes.CDLL(clibs) File "/usr/lib/python3.8/ctypes/init.py", line 373, in init self._handle = _dlopen(self._name, mode) OSError: asset/render.so: cannot open shared object file: No such file or directory

    opened by Algabri 0
  • Memory usage

    Memory usage

    hi @1996scarlet

    Is it expected that the model uses around 18GB of video RAM? Or does it maximises the RAM available to help with speed? (I got a 24GB ram GPU, and usage goes up to 22.2GB while inferencing) Thanks for this amazing MIT license repo btw.

    opened by Tetsujinfr 0
Releases(v1.0)
  • v1.0(Feb 1, 2021)

    Stable Head Pose Estimation and Landmark Regression via 3D Dense Face Reconstruction

    • CPU real-time face deteciton, alignment, and reconstruction pipeline.
    • Lightweight render library, 5x faster (3ms vs 15ms) than the Sim3DR tools.
    • Camera matrix and dense/sparse landmarks prediction via a single network.
    • Generate facial parameters for robust head pose and expression estimation.
    Source code(tar.gz)
    Source code(zip)
Owner
Remilia Scarlet
Remilia Scarlet
Spatial Single-Cell Analysis Toolkit

Single-Cell Image Analysis Package Scimap is a scalable toolkit for analyzing spatial molecular data. The underlying framework is generalizable to spa

Laboratory of Systems Pharmacology @ Harvard 30 Nov 08, 2022
Code for CVPR2019 paper《Unequal Training for Deep Face Recognition with Long Tailed Noisy Data》

Unequal-Training-for-Deep-Face-Recognition-with-Long-Tailed-Noisy-Data. This is the code of CVPR 2019 paper《Unequal Training for Deep Face Recognition

Zhong Yaoyao 68 Jan 07, 2023
Code accompanying the paper "How Tight Can PAC-Bayes be in the Small Data Regime?"

How Tight Can PAC-Bayes be in the Small Data Regime? This is the code to reproduce all experiments for the following paper: @inproceedings{Foong:2021:

5 Dec 21, 2021
TorchMultimodal is a PyTorch library for training state-of-the-art multimodal multi-task models at scale.

TorchMultimodal (Alpha Release) Introduction TorchMultimodal is a PyTorch library for training state-of-the-art multimodal multi-task models at scale.

Meta Research 663 Jan 06, 2023
Rethinking Semantic Segmentation from a Sequence-to-Sequence Perspective with Transformers

Segmentation Transformer Implementation of Segmentation Transformer in PyTorch, a new model to achieve SOTA in semantic segmentation while using trans

Abhay Gupta 161 Dec 08, 2022
The sixth place winning solution (6/220) in 2021 Gaofen Challenge.

SwinTransformer + OBBDet The sixth place winning solution (6/220) in the track of Fine-grained Object Recognition in High-Resolution Optical Images, 2

ming71 46 Dec 02, 2022
Self-training with Weak Supervision (NAACL 2021)

This repo holds the code for our weak supervision framework, ASTRA, described in our NAACL 2021 paper: "Self-Training with Weak Supervision"

Microsoft 148 Nov 20, 2022
HiddenMarkovModel implements hidden Markov models with Gaussian mixtures as distributions on top of TensorFlow

Class HiddenMarkovModel HiddenMarkovModel implements hidden Markov models with Gaussian mixtures as distributions on top of TensorFlow 2.0 Installatio

Susara Thenuwara 2 Nov 03, 2021
Supporting code for the paper "Dangers of Bayesian Model Averaging under Covariate Shift"

Dangers of Bayesian Model Averaging under Covariate Shift This repository contains the code to reproduce the experiments in the paper Dangers of Bayes

Pavel Izmailov 25 Sep 21, 2022
Annotated, understandable, and visually interpretable PyTorch implementations of: VAE, BIRVAE, NSGAN, MMGAN, WGAN, WGANGP, LSGAN, DRAGAN, BEGAN, RaGAN, InfoGAN, fGAN, FisherGAN

Overview PyTorch 0.4.1 | Python 3.6.5 Annotated implementations with comparative introductions for minimax, non-saturating, wasserstein, wasserstein g

Shayne O'Brien 471 Dec 16, 2022
🐦 Quickly annotate data from the comfort of your Jupyter notebook

🐦 pigeon - Quickly annotate data on Jupyter Pigeon is a simple widget that lets you quickly annotate a dataset of unlabeled examples from the comfort

Anastasis Germanidis 647 Jan 05, 2023
Developed an optimized algorithm which finds the most optimal path between 2 points in a 3D Maze using various AI search techniques like BFS, DFS, UCS, Greedy BFS and A*

Developed an optimized algorithm which finds the most optimal path between 2 points in a 3D Maze using various AI search techniques like BFS, DFS, UCS, Greedy BFS and A*. The algorithm was extremely

1 Mar 28, 2022
Official page of Patchwork (RA-L'21 w/ IROS'21)

Patchwork Official page of "Patchwork: Concentric Zone-based Region-wise Ground Segmentation with Ground Likelihood Estimation Using a 3D LiDAR Sensor

Hyungtae Lim 254 Jan 05, 2023
an Evolutionary Algorithm assisted GAN

EvoGAN an Evolutionary Algorithm assisted GAN ckpts

3 Oct 09, 2022
git《Pseudo-ISP: Learning Pseudo In-camera Signal Processing Pipeline from A Color Image Denoiser》(2021) GitHub: [fig5]

Pseudo-ISP: Learning Pseudo In-camera Signal Processing Pipeline from A Color Image Denoiser Abstract The success of deep denoisers on real-world colo

Yue Cao 51 Nov 22, 2022
EPSANet:An Efficient Pyramid Split Attention Block on Convolutional Neural Network

EPSANet:An Efficient Pyramid Split Attention Block on Convolutional Neural Network This repo contains the official Pytorch implementaion code and conf

Hu Zhang 175 Jan 07, 2023
The Pytorch implementation for "Video-Text Pre-training with Learned Regions"

Region_Learner The Pytorch implementation for "Video-Text Pre-training with Learned Regions" (arxiv) We are still cleaning up the code further and pre

Rui Yan 0 Mar 20, 2022
[arXiv] What-If Motion Prediction for Autonomous Driving ❓🚗💨

WIMP - What If Motion Predictor Reference PyTorch Implementation for What If Motion Prediction [PDF] [Dynamic Visualizations] Setup Requirements The W

William Qi 96 Dec 29, 2022
Tiny Kinetics-400 for test

Kinetics-400迷你数据集 English | 简体中文 该数据集旨在解决的问题:参照Kinetics-400数据格式,训练基于自己数据的视频理解模型。 数据集介绍 Kinetics-400是视频领域benchmark常用数据集,详细介绍可以参考其官方网站Kinetics。整个数据集包含40

38 Jan 06, 2023
Official repo for BMVC2021 paper ASFormer: Transformer for Action Segmentation

ASFormer: Transformer for Action Segmentation This repo provides training & inference code for BMVC 2021 paper: ASFormer: Transformer for Action Segme

42 Dec 23, 2022