/ Модель

Характеристики

Лицензия
CC BY-NC 4.0
Библиотека
pytorch
Опубликована
13 ноя 2026

drowsiness-detection-landmarks

Классификация и разметка3 профессии

Модель определяет 98 лицевых ориентиров WFLW для оценки открытости глаз и прототипирования систем обнаружения сонливости.

34скачиваний за 30 дней0лайковвеса обновлены13 ноя 2026

Бенчмарки

Как модель справилась с задачами пользователей ailist и что о ней публикуют открытые лидерборды

Публичные оценки

Из открытых лидербордов. Сравнивайте результаты одного теста при одинаковых условиях — отсутствие оценки не значит, что модель хуже.

В подключённых источниках результатов для этой модели пока нет.

Что умеет модель

Описание составлено по карточке модели и метаданным Hugging Face

Модель находит 98 лицевых ориентиров схемы WFLW на квадратном RGB-кропе лица размером 256 × 256 пикселей. Её разработал автор репозитория arthursilvadantas для оценки открытости глаз по Eye Aspect Ratio (EAR) и последующего анализа морганий и длительного закрытия глаз. Для обнаружения лица в приложении используется отдельный детектор YuNet.

Модель построена на ResNet-18, предварительно обученной на ImageNet и дообученной вместе с головой ориентиров; координаты вычисляются методом soft-argmax. При предсказании применяется тестирование с зеркальным отражением лица. На тестовом наборе WFLW модель показала NME 5,12% и корреляцию EAR 0,725; она обнаружила 67,5% закрытых глаз, при этом 5,2% незакрытых глаз были ошибочно помечены как закрытые.

Модель предназначена для исследований, обучения и прототипов систем мониторинга водителей. Она обучена на фотографиях WFLW, поэтому её поведение на ночных и инфракрасных изображениях может отличаться. Ошибки чаще возникают при сложном ракурсе, крайнем профиле и сильных перекрытиях; низкий EAR также может быть вызван взглядом вниз, улыбкой или прищуриванием. Лицензия CC BY-NC 4.0 запрещает коммерческое использование.

Сценарии применения

  • определение лицевых ориентиров на кропе лица
  • оценка открытости глаз по EAR
  • анализ длительного закрытия глаз в видеопотоке
  • прототипирование мониторинга сонливости водителя
  • эксперименты с распознаванием морганий

Ограничения

На тесте WFLW модель пропустила около трети закрытых глаз и ошибочно отметила закрытыми 5,2% открытых; сложные позы, крайний профиль, перекрытия, ночные и инфракрасные изображения могут ухудшить результат. EAR также снижается при взгляде вниз, улыбке и прищуривании, поэтому модель не подходит как единственная система безопасности автомобиля; лицензия исключает коммерческое использование.

Для каких профессий подходит3

Разделы каталога профессий, в задачах которых используется эта модель

Все профессии

Карточка модели

README от автора на Hugging Face, как он его опубликовал

Открыть на Hugging Face

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.

Taskfacial landmark detection: 98 (x, y) points per face
ModelResNet-18 (ImageNet, fine-tuned) + landmark head trained from scratch + soft-argmax
Inputsquare face crop, 256 × 256, RGB
Face detectorYuNet (OpenCV Zoo), included
Parameters15.4M (head: 4.2M)
WFLW testNME 5.12%, eye NME 3.27%, 67.5% of closed eyes detected
Speedabout 150 ms per image on a laptop CPU, detection and flip TTA included
LicenseCC 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

StepSetting
DataWFLW train split only: 6,737 faces for training and 763 for validation, split by image
BackboneResNet-18 pre-trained on ImageNet, without average pooling and FC, fully fine-tuned
Head3 × (transposed convolution 4 × 4, stride 2, 256 channels, BatchNorm, ReLU) and a 1 × 1 convolution with 98 outputs
LossL1 on the coordinates divided by 256, eye points 60 to 75 weighted ×8
Closed eyesfaces with annotated EAR below 0.15 (about 9% of the training set) sampled 8× more often
Augmentationhorizontal 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)
OptimizerAdamW, learning rate 1e-3 for the head and 2e-4 for the backbone, weight decay 1e-4
Schedule1 warmup epoch, then cosine decay; 80 epochs, batch 32, seed 42
Selectionbest validation NME epoch (69: 4.17%); the variant was chosen among 15 on validation only
HardwareNVIDIA 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.

NMEFailure rate (NME > 10%)Eye NMEEAR correlationClosed eyes detectedNon-closed eyes flagged as closed
Baseline5.05%6.08%3.53%0.64423.4%1.0%
Final model5.12%6.68%3.27%0.72567.5%5.2%

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

SubsetPoseExpressionIlluminationMake-upOcclusionBlur
NME, final model9.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.

Tarefadetecção de pontos faciais: 98 pontos (x, y) por face
ModeloResNet-18 (ImageNet, com ajuste fino) + cabeça de landmarks treinada do zero + soft-argmax
Entradarecorte quadrado da face, 256 × 256, RGB
Detector de facesYuNet (OpenCV Zoo), incluído
Parâmetros15,4 milhões (cabeça: 4,2 milhões)
Teste do WFLWNME 5,12%, NME dos olhos 3,27%, 67,5% dos olhos fechados reconhecidos
Velocidadecerca de 150 ms por imagem numa CPU de notebook, já contando a detecção e o TTA
LicençaCC 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

EtapaConfiguração
Dadossó o treino do WFLW: 6.737 faces para treinar e 763 para validar, separadas por imagem
BackboneResNet-18 pré-treinada na ImageNet, sem average pooling e FC, com ajuste fino completo
Cabeça3 × (convolução transposta 4 × 4, passo 2, 256 canais, BatchNorm, ReLU) e uma convolução 1 × 1 com 98 saídas
PerdaL1 nas coordenadas dividida por 256, com peso 8 nos pontos dos olhos (60 a 75)
Olhos fechadosfaces com EAR anotado abaixo de 0,15 (cerca de 9% do treino) sorteadas 8 vezes mais
Augmentationespelhamento 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)
OtimizadorAdamW, taxa de aprendizagem 1e-3 na cabeça e 2e-4 no backbone, weight decay 1e-4
Agenda1 é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
HardwareNVIDIA 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.

NMETaxa de falha (NME > 10%)NME dos olhosCorrelação do EAROlhos fechados reconhecidosOlhos não fechados marcados como fechados
Baseline5,05%6,08%3,53%0,64423,4%1,0%
Modelo final5,12%6,68%3,27%0,72567,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).

SubconjuntoPoseExpressãoIluminaçãoMaquiagemOclusãoDesfoque
NME do modelo final9,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.

Как запустить

На своей GPU в ailist. Цена — по текущим предложениям провайдеров

GPU в ailist

Универсальный рантайм · pytorch

Нельзя запустить

Библиотека «pytorch» рантаймом не поддерживается.

Ревизия весов
b36a9b2

0 моделей