Facial landmarks (98 points, WFLW) for drowsiness detection

English · Português

English

This model finds the 98 facial landmarks of the WFLW scheme on each face of an image. It was built to measure how open the eyes are (the Eye Aspect Ratio, EAR) in a drowsiness detection application: a temporal analysis of the EAR tells a normal blink from a prolonged eye closure.

Task facial landmark detection: 98 (x, y) points per face
Model ResNet-18 (ImageNet, fine-tuned) + landmark head trained from scratch + soft-argmax
Input square face crop, 256 × 256, RGB
Face detector YuNet (OpenCV Zoo), included
Parameters 15.4M (head: 4.2M)
WFLW test NME 5.12%, eye NME 3.27%, 67.5% of closed eyes detected
Speed about 150 ms per image on a laptop CPU, detection and flip TTA included
License CC BY-NC 4.0, non-commercial (why)

Code, notebooks and the video application: GitHub.

EAR over time on a webcam video

Files

├── modelo.pt                                   model weights and training config
├── config.yaml                                 hyper-parameters used in training
├── predict.py                                  LandmarkModel: image ─► (N, 98, 2)
├── utils.py                                    model, crop and detector code used by predict.py
├── models/face_detection_yunet_2023mar.onnx    YuNet face detector
└── images/                                     figures of this card

Quick start

pip install torch torchvision opencv-python numpy huggingface_hub
hf download arthursilvadantas/drowsiness-detection-landmarks --local-dir landmarks
cd landmarks
import cv2
from predict import LandmarkModel

model = LandmarkModel("modelo.pt", device="cpu")
image = cv2.cvtColor(cv2.imread("photo.jpg"), cv2.COLOR_BGR2RGB)
landmarks = model.predict(image)   # (N, 98, 2), pixels of the full image, N = faces found

Nothing is downloaded at prediction time: the backbone is rebuilt from the checkpoint and YuNet is read from models/. The video application (webcam, EAR, blink and alert) is in the GitHub repository (app.py).

How it works

image ─► YuNet finds the faces ─► square crop (1.25 × longest box side) ─► 256 × 256
      ─► ResNet-18 ─► 3 transposed convolutions ─► 98 heatmaps of 64 × 64
      ─► soft-argmax ─► 98 points in the crop ─► inverse transform ─► points in the full image
  • Soft-argmax takes the expected position under a spatial softmax, so the coordinates are sub-pixel and the loss is computed directly on them. This matters for the eyes: an open eye is only about 10 pixels tall in the 256 crop.
  • Flip TTA: the face is also predicted mirrored, the mirrored points are mapped back with the WFLW Mirror98 order, and both predictions are averaged.
  • Landmark order follows WFLW: 0 to 32 contour, 33 to 50 eyebrows, 51 to 59 nose, 60 to 75 eyes (60 to 67 is the person's right eye, on the left of the image), 76 to 95 mouth, 96 and 97 pupils.
  • EAR with points (60, 61, 63, 64, 65, 67) and (72, 71, 69, 68, 75, 73), averaged over both eyes.

Training

Step Setting
Data WFLW train split only: 6,737 faces for training and 763 for validation, split by image
Backbone ResNet-18 pre-trained on ImageNet, without average pooling and FC, fully fine-tuned
Head 3 × (transposed convolution 4 × 4, stride 2, 256 channels, BatchNorm, ReLU) and a 1 × 1 convolution with 98 outputs
Loss L1 on the coordinates divided by 256, eye points 60 to 75 weighted ×8
Closed eyes faces with annotated EAR below 0.15 (about 9% of the training set) sampled 8× more often
Augmentation horizontal flip with Mirror98 reordering, rotation ±15°, scale 0.85 to 1.2, translation 6%, brightness and contrast, low resolution (downscale 2 to 4× and back, 30% of the time)
Optimizer AdamW, learning rate 1e-3 for the head and 2e-4 for the backbone, weight decay 1e-4
Schedule 1 warmup epoch, then cosine decay; 80 epochs, batch 32, seed 42
Selection best validation NME epoch (69: 4.17%); the variant was chosen among 15 on validation only
Hardware NVIDIA RTX A6000

Results

WFLW official test split, 2,500 faces never used in training or model selection. NME is the mean point error divided by the distance between the outer eye corners (points 60 and 72). Both models use flip TTA; the baseline has the same architecture without any closed-eye handling.

NME Failure rate (NME > 10%) Eye NME EAR correlation Closed eyes detected Non-closed eyes flagged as closed
Baseline 5.05% 6.08% 3.53% 0.644 23.4% 1.0%
Final model 5.12% 6.68% 3.27% 0.725 67.5% 5.2%

A face counts as closed when its EAR is below 0.15 (annotated: 274 closed, 2,226 not closed).

Subset Pose Expression Illumination Make-up Occlusion Blur
NME, final model 9.22% 5.53% 5.05% 5.23% 6.28% 5.89%

With the YuNet detector instead of the annotated boxes: 97.8% of the faces found, 5.08% NME and 3.14% eye NME, so the crop used in the application matches the one used in training.

EAR: annotated vs. predicted

Limitations

  • Trade-off: compared to the baseline, the overall NME is 0.07 pt higher and a few more open eyes are flagged as closed, in exchange for detecting about three times more closed eyes.
  • Head pose is the hardest case (9.2% NME); extreme profiles and heavy occlusions are the typical failures, and some of them are not found by YuNet at all.
  • The EAR is not only about sleepiness: it also drops when looking down, smiling or squinting.
  • Trained only on WFLW photos; night or infrared images may behave differently.

Intended use

  • Suitable: research, teaching, prototypes of driver monitoring.
  • Not suitable: as the only safety system in a vehicle, or any commercial use.

License

CC BY-NC 4.0. The model was trained on WFLW, released for non-commercial research use, so the weights follow the same restriction. WFLW: Wu et al., Look at Boundary: A Boundary-Aware Face Alignment Algorithm, CVPR 2018. YuNet: OpenCV Zoo, MIT License.


Português

Este modelo encontra os 98 pontos faciais do esquema do WFLW em cada face de uma imagem. Ele foi feito para medir o quanto os olhos estão abertos (o Eye Aspect Ratio, EAR) numa aplicação de detecção de sonolência: uma análise do EAR ao longo do tempo separa uma piscada normal de um fechamento prolongado dos olhos.

Tarefa detecção de pontos faciais: 98 pontos (x, y) por face
Modelo ResNet-18 (ImageNet, com ajuste fino) + cabeça de landmarks treinada do zero + soft-argmax
Entrada recorte quadrado da face, 256 × 256, RGB
Detector de faces YuNet (OpenCV Zoo), incluído
Parâmetros 15,4 milhões (cabeça: 4,2 milhões)
Teste do WFLW NME 5,12%, NME dos olhos 3,27%, 67,5% dos olhos fechados reconhecidos
Velocidade cerca de 150 ms por imagem numa CPU de notebook, já contando a detecção e o TTA
Licença CC BY-NC 4.0, uso não comercial (por quê)

Código, notebooks e a aplicação em vídeo: GitHub.

Arquivos

├── modelo.pt                                   pesos do modelo e configuração do treino
├── config.yaml                                 hiperparâmetros usados no treino
├── predict.py                                  LandmarkModel: imagem ─► (N, 98, 2)
├── utils.py                                    código do modelo, do recorte e do detector usado pelo predict.py
├── models/face_detection_yunet_2023mar.onnx    detector de faces YuNet
└── images/                                     figuras deste card

Início rápido

pip install torch torchvision opencv-python numpy huggingface_hub
hf download arthursilvadantas/drowsiness-detection-landmarks --local-dir landmarks
cd landmarks
import cv2
from predict import LandmarkModel

model = LandmarkModel("modelo.pt", device="cpu")
image = cv2.cvtColor(cv2.imread("foto.jpg"), cv2.COLOR_BGR2RGB)
landmarks = model.predict(image)   # (N, 98, 2), pixels da imagem inteira, N = faces encontradas

Nada é baixado na hora de prever: o backbone é reconstruído a partir do checkpoint e o YuNet é lido da pasta models/. A aplicação em vídeo (webcam, EAR, piscadas e alerta) está no repositório do GitHub (app.py).

Como funciona

imagem ─► YuNet encontra as faces ─► recorte quadrado (1,25 × maior lado) ─► 256 × 256
       ─► ResNet-18 ─► 3 convoluções transpostas ─► 98 mapas de calor de 64 × 64
       ─► soft-argmax ─► 98 pontos no recorte ─► transformação inversa ─► pontos na imagem inteira
  • O soft-argmax calcula a posição média ponderada por um softmax no mapa, então as coordenadas saem com precisão abaixo de um pixel e a perda é calculada direto nelas. Isso importa para os olhos: um olho aberto tem só uns 10 pixels de altura no recorte de 256.
  • TTA com espelhamento: a face também é prevista espelhada, os pontos espelhados voltam para a ordem certa com o Mirror98 do WFLW, e as duas previsões são combinadas pela média.
  • A ordem dos pontos segue o WFLW: 0 a 32 contorno, 33 a 50 sobrancelhas, 51 a 59 nariz, 60 a 75 olhos (60 a 67 é o olho direito da pessoa, que aparece à esquerda na imagem), 76 a 95 boca, 96 e 97 pupilas.
  • O EAR usa os pontos (60, 61, 63, 64, 65, 67) e (72, 71, 69, 68, 75, 73), com a média dos dois olhos.

Treino

Etapa Configuração
Dados só o treino do WFLW: 6.737 faces para treinar e 763 para validar, separadas por imagem
Backbone ResNet-18 pré-treinada na ImageNet, sem average pooling e FC, com ajuste fino completo
Cabeça 3 × (convolução transposta 4 × 4, passo 2, 256 canais, BatchNorm, ReLU) e uma convolução 1 × 1 com 98 saídas
Perda L1 nas coordenadas dividida por 256, com peso 8 nos pontos dos olhos (60 a 75)
Olhos fechados faces com EAR anotado abaixo de 0,15 (cerca de 9% do treino) sorteadas 8 vezes mais
Augmentation espelhamento horizontal com reordenação pelo Mirror98, rotação de 15°, escala de 0,85 a 1,2, deslocamento de 6%, brilho e contraste, baixa resolução (reduz 2 a 4 vezes e amplia de volta, em 30% das vezes)
Otimizador AdamW, taxa de aprendizagem 1e-3 na cabeça e 2e-4 no backbone, weight decay 1e-4
Agenda 1 época de warmup e depois decaimento em cosseno; 80 épocas, lote 32, semente 42
Escolha época com menor NME na validação (69: 4,17%); a variante foi escolhida entre 15 só pela validação
Hardware NVIDIA RTX A6000

Resultados

Teste oficial do WFLW, 2.500 faces que nunca foram usadas no treino nem na escolha do modelo. O NME é o erro médio dos pontos dividido pela distância entre os cantos de fora dos olhos (pontos 60 e 72). Os dois modelos usam TTA; o baseline tem a mesma arquitetura, sem nenhum tratamento para olhos fechados.

NME Taxa de falha (NME > 10%) NME dos olhos Correlação do EAR Olhos fechados reconhecidos Olhos não fechados marcados como fechados
Baseline 5,05% 6,08% 3,53% 0,644 23,4% 1,0%
Modelo final 5,12% 6,68% 3,27% 0,725 67,5% 5,2%

Uma face conta como fechada quando o EAR fica abaixo de 0,15 (anotadas: 274 fechadas e 2.226 não fechadas).

Subconjunto Pose Expressão Iluminação Maquiagem Oclusão Desfoque
NME do modelo final 9,22% 5,53% 5,05% 5,23% 6,28% 5,89%

Com o detector YuNet no lugar dos retângulos anotados: 97,8% das faces encontradas, NME de 5,08% e NME dos olhos de 3,14%, ou seja, o recorte usado na aplicação é compatível com o do treino.

Limitações

  • Compromisso: em relação ao baseline, o NME geral fica 0,07 ponto maior e alguns olhos abertos a mais são marcados como fechados, em troca de reconhecer cerca de três vezes mais olhos fechados.
  • Cabeça virada é o caso mais difícil (NME de 9,2%); perfis extremos e faces muito encobertas são as falhas típicas, e algumas nem são encontradas pelo YuNet.
  • O EAR não depende só do sono: ele também cai quando a pessoa olha para baixo, sorri ou aperta os olhos.
  • Treinado só com fotos do WFLW; imagens noturnas ou infravermelhas podem se comportar diferente.

Uso recomendado

  • Adequado: pesquisa, ensino e protótipos de monitoramento de motoristas.
  • Não adequado: como único sistema de segurança num veículo, ou qualquer uso comercial.

Licença

CC BY-NC 4.0. O modelo foi treinado com o WFLW, liberado para pesquisa sem fins comerciais, então os pesos seguem a mesma restrição. WFLW: Wu et al., Look at Boundary: A Boundary-Aware Face Alignment Algorithm, CVPR 2018. YuNet: OpenCV Zoo, licença MIT.

Downloads last month
32
Inference Providers NEW
This model isn't deployed by any Inference Provider. 🙋 Ask for provider support

Space using arthursilvadantas/drowsiness-detection-landmarks 1

Evaluation results

  • NME inter-ocular (%), lower is better on WFLW, official test split (2,500 faces), annotated face boxes, flip TTA
    test set self-reported
    5.120
  • Eye NME inter-ocular (%), lower is better on WFLW, official test split (2,500 faces), annotated face boxes, flip TTA
    test set self-reported
    3.270
  • Failure rate at 10% NME (%), lower is better on WFLW, official test split (2,500 faces), annotated face boxes, flip TTA
    test set self-reported
    6.680
  • NME inter-ocular (%), lower is better on WFLW, official test split, faces found by YuNet, flip TTA
    test set self-reported
    5.080
  • Faces detected (%) on WFLW, official test split, faces found by YuNet, flip TTA
    test set self-reported
    97.800
  • Closed eyes detected (%) on WFLW test faces with annotated EAR below 0.15 (274)
    test set self-reported
    67.500