Оценка лиц
Сейчас в Face SDK реализован API процессинг-блоков – новый масштабируемый интерфейс, призванный в перспективе заместить существующие API. Планируется, что поддержка API, представленного в этом разделе, будет прекращена в 2024 году.
- Пол и возраст
- Эмоции
- Качество изображения лица
- Liveness (2D и 3D)
- Детекция маски
- Состояние глаз (открыты/закрыты)
Пол и возраст
Для оценки пола и возраста лица на изображении выполните следующие действия:
Создайте объект
AgeGenderEstimator, вызвав методFacerecService.createAgeGenderEstimator. В качестве аргумента передайте один из файлов конфигурации, перечисленных ниже:age_gender_estimator.xml– первоначальная реализация интерфейса оценки пола и возраста AgeGenderEstimator.age_gender_estimator_v2.xml– улучшенная версия интерфейса оценки пола и возраста AgeGenderEstimator, обеспечивает большую точность оценок при условии соблюдения рекомендаций по съемке.age_gender_estimator_v3.xml– улучшенная версия интерфейса оценки пола и возраста, доступна для 64-разрядной версии Windows x86, 64-разрядной версии Linux x86 и Android.
Чтобы определить пол и возраст лица, вызовите метод
AgeGenderEstimator.estimateAgeGender. Метод возвращает структуру типаAgeGenderEstimator.AgeGender, которая содержит значение пола (AgeGenderEstimator.Gender), возрастную группу (AgeGenderEstimator.Age) и значение возраста в годах (float).
Всего доступны 4 возрастные группы:
- KID – возраст от 0 до 18 лет.
- YOUNG – возраст от 18 до 37 лет.
- ADULT – возраст от 37 до 55 лет.
- SENIOR – возраст от 55 и старше.
- C++
- C#
- Java
- Python
// создание объекта AgeGenderEstimator
const pbio::AgeGenderEstimator::Ptr age_gender_estimator = service->createAgeGenderEstimator("age_gender_estimator.xml");
// детекция лиц
std::vector<pbio::RawSample::Ptr> samples = capturer->capture(image);
for(size_t i = 0; i < samples.size(); ++i)
{
// оценка пола и возраста
const pbio::AgeGenderEstimator::AgeGender age_gender = age_gender_estimator->estimateAgeGender(*samples[i]);
}
// создание объекта AgeGenderEstimator
AgeGenderEstimator age_gender_estimator = service.createAgeGenderEstimator("age_gender_estimator.xml");
// детекция лиц
List<RawSample> samples = capturer.capture(image);
for(int i = 0; i < samples.Count; ++i)
{
RawSample sample = samples[i];
// оценка пола и возраста
AgeGenderEstimator.AgeGender age_gender = age_gender_estimator.estimateAgeGender(sample);
}
// создание объекта AgeGenderEstimator
AgeGenderEstimator age_gender_estimator = service.createAgeGenderEstimator("age_gender_estimator.xml");
// детекция лиц
Vector<RawSample> samples = capturer.capture(image);
for(int i = 0; i < samples.size(); i++)
{
RawSample sample = samples.get(i);
// оценка пола и возраста
AgeGenderEstimator.AgeGender age_gender = age_gender_estimator.estimateAgeGender(sample);
}
# создание объекта AgeGenderEstimator
age_gender_estimator = service.create_age_gender_estimator("age_gender_estimator.xml")
# детекция лиц
samples = capturer.capture(image)
for sample in samples:
# оценка пола и возраста
age_gender = age_gender_estimator.estimate_age_gender(sample)
Пример использования AgeGenderEstimator см. в demo.cpp. Также узнать о том, как определить пол и возраст лица с помощью Face SDK, можно в нашем туториале.
Для оценки пола и возраста через API процессинг-блоков см. раздел Оценка лиц.
Эмоции
Для оценки эмоций по лицу на изображении выполните следующие шаги:
Создайте объект
EmotionsEstimator, вызвав методFacerecService.createEmotionsEstimator. В качестве аргумента передайте один из двух доступных файлов конфигурации:emotions_estimator.xml- позволяет оценить четыре эмоции' лица: happy (радость), surprised (удивление), neutral (спокойствие), angry (гнев).emotions_estimator_v2.xml- позволяет оценить семь эмоций лица: happy (радость), surprised (удивление), neutral (спокойствие), angry (гнев), disgusted (отвращение), sad (грусть), scared (страх).
Для оценки эмоций вызовите метод
EmotionsEstimator.estimateEmotions. Результатом будет массив элементов типаEmotionsEstimator.EmotionConfidence, содержащих название эмоции и оценку уверенности.
- C++
- C#
- Java
- Python
// создание объекта EmotionsEstimator
const pbio::EmotionsEstimator::Ptr emotions_estimator = service->createEmotionsEstimator("emotions_estimator.xml");
// детекция лиц
std::vector<pbio::RawSample::Ptr> samples = capturer->capture(image);
for(size_t i = 0; i < samples.size(); ++i)
{
// оценка эмоций
const std::vector<pbio::EmotionsEstimator::EmotionConfidence> emotions = emotions_estimator->estimateEmotions(*samples[i]);
}
// создание объекта EmotionsEstimator
EmotionsEstimator emotions_estimator = service.createEmotionsEstimator("emotions_estimator.xml");
// детекция лиц
List<RawSample> samples = capturer.capture(image);
for(int i = 0; i < samples.Count; ++i)
{
RawSample sample = samples[i];
// оценка эмоций
List<EmotionsEstimator.EmotionConfidence> emotions = emotions_estimator.estimateEmotions(sample);
}
// создание объекта EmotionsEstimator
EmotionsEstimator emotions_estimator = service.createEmotionsEstimator("emotions_estimator.xml");
// детекция лиц
Vector<RawSample> samples = capturer.capture(image);
for(int i = 0; i < samples.size(); i++)
{
RawSample sample = samples.get(i);
// оценка эмоций
Vector<EmotionsEstimator.EmotionConfidence> emotions = emotions_estimator.estimateAgeGender(sample);
}
# создание объекта EmotionsEstimator
emotions_estimator = service.create_emotions_estimator("emotions_estimator.xml")
# детекция лиц
samples = capturer.capture(image)
for sample in samples:
# оценка эмоций
emotions = emotions_estimator.estimate_emotions(sample)
Пример использования EmotionsEstimator см. в demo.cpp.
Для определения эмоций через API процессинг-блоков см. раздел Оценка эмоций.
Более подробно об оценке пола, возраста и эмоций лиц на видеопотоке см. в разделе Обработка видеопотока.
Качество изображения лица
Для оценки качества изображений доступны два класса: QualityEstimator и FaceQualityEstimator.
QualityEstimatorпредоставляет дискретные оценки качества: степень засветки, равномерность освещения, уровень шума и резкости.FaceQualityEstimatorпредоставляет качество в виде единственного вещественного числа, агрегирующего качество освещения, размытие, шум и ракурс, что очень удобно для сравнения качества изображений, полученных от трекера.
Для оценки качества изображения через API процессинг-блоков см. раздел Блок проверки качества фото.
QualityEstimator
Создайте объект
QualityEstimator, вызвав методFacerecService.createQualityEstimator. В качестве аргумента передайте один из двух доступных файлов конфигурации:quality_estimator.xml– первоначальная реализация интерфейса оценки качества QualityEstimator.quality_estimator_iso.xml(рекомендуемый) – улучшенная версия интерфейса оценки качества QualityEstimator, обеспечивает большую точность оценок качества.
Чтобы определить качество изображения лица, вызовите метод
QualityEstimator.estimateQuality. Метод возвращает структуру типаQualityEstimator.Quality, которая содержит оценки засветки (flare), равномерности освещения (lighting), шума (noise) и резкости (sharpness).
- C++
- C#
- Java
- Python
// создание объекта QualityEstimator
const pbio::QualityEstimator::Ptr quality_estimator = service->createQualityEstimator("quality_estimator_iso.xml");
// детекция лиц
std::vector<pbio::RawSample::Ptr> samples = capturer->capture(image);
for(size_t i = 0; i < samples.size(); ++i)
{
// оценка качества изображения
const pbio::QualityEstimator::Quality quality = quality_estimator->estimateQuality(*samples[i]);
}
// создание объекта QualityEstimator
QualityEstimator quality_estimator = service.createQualityEstimator("quality_estimator_iso.xml");
// детекция лиц
List<RawSample> samples = capturer.capture(image);
for(int i = 0; i < samples.Count; ++i)
{
RawSample sample = samples[i];
// оценка качества изображения
QualityEstimator.Quality quality = quality_estimator.estimateQuality(sample);
}
// создание объекта QualityEstimator
QualityEstimator quality_estimator = service.createQualityEstimator("quality_estimator_iso.xml");
// детекция лиц
Vector<RawSample> samples = capturer.capture(image);
for(int i = 0; i < samples.size(); i++)
{
RawSample sample = samples.get(i);
// оценка качества изображения
QualityEstimator.Quality quality = quality_estimator.estimateQuality(sample);
}
# создание объекта QualityEstimator
quality_estimator = service.create_quality_estimator("quality_estimator_iso.xml")
# детекция лиц
samples = capturer.capture(image)
for sample in samples:
# оценка качества изображения
quality = quality_estimator.estimate_quality(sample)
Пример использования QualityEstimator см. в demo.cpp.
FaceQualityEstimator
- Создайте объект
FaceQualityEstimator, вызвав методFacerecService.createFaceQualityEstimator. В качестве аргумента передайте файл конфигурацииface_quality_estimator.xml. - Чтобы определить качество изображения лица, вызовите метод
FaceQualityEstimator.estimateQuality. Результатом будет вещественное число (значение может быть отрицательным), агрегирующее качество освещения, размытие, шум и ракурс (чем выше значение, тем выше качество).
- C++
- C#
- Java
- Python
// создание объекта FaceQualityEstimator
const pbio::FaceQualityEstimator::Ptr face_quality_estimator = service->createFaceQualityEstimator("face_quality_estimator.xml");
// детекция лиц
std::vector<pbio::RawSample::Ptr> samples = capturer->capture(image);
for(size_t i = 0; i < samples.size(); ++i)
{
// оценка качества изображения лица
const pbio::FaceQualityEstimator::Quality face_quality = face_quality_estimator->estimateQuality(*samples[i]);
}
// создание объекта FaceQualityEstimator
FaceQualityEstimator face_quality_estimator = service.createFaceQualityEstimator("face_quality_estimator.xml");
// детекция лиц
List<RawSample> samples = capturer.capture(image);
for(int i = 0; i < samples.Count; ++i)
{
RawSample sample = samples[i];
// оценка качества изображения лица
FaceQualityEstimator.Quality face_quality = face_quality_estimator.estimateQuality(sample);
}
// создание объекта FaceQualityEstimator
FaceQualityEstimator face_quality_estimator = service.createFaceQualityEstimator("face_quality_estimator.xml");
// детекция лиц
Vector<RawSample> samples = capturer.capture(image);
for(int i = 0; i < samples.size(); i++)
{
RawSample sample = samples.get(i);
// оценка качества изображения
float face_quality = face_quality_estimator.estimateQuality(sample);
}
# создание объекта FaceQualityEstimator
face_quality_estimator = service.create_face_quality_estimator("face_quality_estimator.xml")
# детекция лиц
samples = capturer.capture(image)
for sample in samples:
# оценка качества изображения лица
face_quality = face_quality_estimator.estimate_quality(sample)
Пример использования FaceQualityEstimator см. в demo.cpp.
Liveness
Технология liveness широко применяется для предотвращения спуфинг-атак с использованием распечатанных изображений, фото или видео лиц с экранов мобильных устройств и мониторов, а также разного рода масок (бумажных, силиконовых и др.).
Face SDK позволяет определить принадлежность лица реальному человеку тремя способами – посредством анализа карты глубины, анализа ИК изображения с камеры, либо через анализ цветного изображения с камеры.
Также доступна оценка liveness с помощью активной (сценарной) проверки, в ходе которой пользователю необходимо выполнить последовательность определенных действий (например, "повернуть голову", "улыбнуться", "моргнуть" и т.д.).
Узнать о том, как определить принадлежность лица реальному человеку с помощью Face SDK, можно в нашем туториале.
Технология liveness корректно работает только с сырыми данными, т.е. изображениями, полученными с камеры. В случае если перед подачей в Liveness Estimator изображение было отредактировано с помощью внешних программных средств (например, подвергнуто ретушированию), корректность работы liveness не гарантирутся, что регламентировано стандартом ISO/IEC 30107-1:2016.
Для оценки живости через API процессинг-блоков см. раздел Блок оценки живости.
DepthLivenessEstimator
Для оценки живости с использованием карты глубины создайте объект
DepthLivenessEstimator, вызвав методFacerecService.createDepthLivenessEstimator. В качестве аргумента укажите один из двух доступных файлов конфигурации:depth_liveness_estimator.xml– первая реализация, не рекомендована к использованию (предназначена только для сохранения обратной совместимости).depth_liveness_estimator_cnn.xml– реализация на основе нейронных сетей, рекомендуемый вариант (используется вVideoWorkerпо умолчанию).
Для получения оценки вызовите метод
DepthLivenessEstimator.estimateLiveness. В качестве аргумента передайтеsample(образец лица) иdepth_map(карту глубины). Карта глубины должна быть синхронизирована и отрегистрирована в соответствии с исходным изображением, на котором было обнаружено лицо. Метод вернет один из нижеперечисленных результатов:DepthLivenessEstimator.Liveness.NOT_ENOUGH_DATA– слишком много отсутствующих значений на карте глубины.DepthLivenessEstimator.Liveness.REAL– наблюдаемое лицо принадлежит живому человеку.DepthLivenessEstimator.Liveness.FAKE– наблюдаемое лицо является фотографией.
- C++
- C#
- Java
- Python
// создание объекта DepthLivenessEstimator
const pbio::DepthLivenessEstimator::Ptr depth_liveness_estimator = service->createDepthLivenessEstimator("depth_liveness_estimator_cnn.xml");
// детекция лиц
std::vector<pbio::RawSample::Ptr> samples = capturer->capture(image);
for(size_t i = 0; i < samples.size(); ++i)
{
// оценка liveness
const pbio::DepthLivenessEstimator::Liveness depth_liveness = depth_liveness_estimator->estimateLiveness(sample, depth_map);
}
// создание объекта DepthLivenessEstimator
DepthLivenessEstimator depth_liveness_estimator = service.createDepthLivenessEstimator("depth_liveness_estimator_cnn.xml");
// детекция лиц
List<RawSample> samples = capturer.capture(image);
for(int i = 0; i < samples.Count; ++i)
{
RawSample sample = samples[i];
// оценка liveness
DepthLivenessEstimator.Liveness depth_liveness = depth_liveness_estimator.estimateLiveness(sample, depth_map);
}
// создание объекта DepthLivenessEstimator
DepthLivenessEstimator depth_liveness_estimator = service.createDepthLivenessEstimator("depth_liveness_estimator_cnn.xml");
// детекция лиц
Vector<RawSample> samples = capturer.capture(image);
for(int i = 0; i < samples.size(); i++)
{
RawSample sample = samples.get(i);
// оценка liveness
DepthLivenessEstimator.Liveness depth_liveness = depth_liveness_estimator.estimateLiveness(sample, depth_map);
}
# создание объекта DepthLivenessEstimator
depth_liveness_estimator = service.create_depth_liveness_estimator("depth_liveness_estimator_cnn.xml")
# детекция лиц
samples = capturer.capture(image)
for sample in samples:
# оценка liveness
depth_liveness = depth_liveness_estimator.estimate_liveness(sample, depth_map)
IRLivenessEstimator
Для оценки живости с использованием инфракрасного изображения с камеры создайте объект
IRLivenessEstimator, вызвав методFacerecService.createIRLivenessEstimator. В качестве аргумента передайте файл конфигурацииir_liveness_estimator_cnn.xml(реализация на основе нейронных сетей). Помимо ИК изображения для использования данного алгоритма также необходимо получать цветные кадры с камеры.Для получения оценки вызовите метод
IRLivenessEstimator.estimateLiveness, передав в качестве аргументовsample(образец лица) иir_frame(инфракрасный кадр). Метод вернет один из нижеперечисленных результатов:IRLivenessEstimator.Liveness.NOT_ENOUGH_DATA– слишком много отсутствующих значений на ИК изображенииIRLivenessEstimator.Liveness.REAL– наблюдаемое лицо принадлежит живому человекуIRLivenessEstimator.Liveness.FAKE– наблюдаемое лицо является фотографией
- C++
- C#
- Java
- Python
// создание объекта IRLivenessEstimator
const pbio::IRLivenessEstimator::Ptr ir_liveness_estimator = service->createIRLivenessEstimator("ir_liveness_estimator_cnn.xml");
// детекция лиц
std::vector<pbio::RawSample::Ptr> samples = capturer->capture(image);
for(size_t i = 0; i < samples.size(); ++i)
{
// оценка liveness
const pbio::IRLivenessEstimator::Liveness ir_liveness = ir_liveness_estimator->estimateLiveness(sample, ir_frame);
}
// создание объекта IRLivenessEstimator
IRLivenessEstimator ir_liveness_estimator = service.createIRLivenessEstimator("ir_liveness_estimator_cnn.xml");
// детекция лиц
List<RawSample> samples = capturer.capture(image);
for(int i = 0; i < samples.Count; ++i)
{
RawSample sample = samples[i];
// оценка liveness
IRLivenessEstimator.Liveness ir_liveness = ir_liveness_estimator.estimateLiveness(sample, ir_frame);
}
// создание объекта IRLivenessEstimator
IRLivenessEstimator ir_liveness_estimator = service.createIRLivenessEstimator("ir_liveness_estimator_cnn.xml");
// детекция лиц
Vector<RawSample> samples = capturer.capture(image);
for(int i = 0; i < samples.size(); i++)
{
RawSample sample = samples.get(i);
// оценка liveness
IRLivenessEstimator.Liveness ir_liveness = ir_liveness_estimator.estimateLiveness(sample, ir_frame);
}
# создание объекта IRLivenessEstimator
ir_liveness_estimator = service.create_ir_liveness_estimator("ir_liveness_estimator_cnn.xml")
# детекция лиц
samples = capturer.capture(image)
for sample in samples:
# оценка liveness
ir_liveness = ir_liveness_estimator.estimate_liveness(sample, ir_frame)
Liveness2DEstimator
Для оценки liveness с использованием цветного изображения с камеры необходимо создать объект
Liveness2DEstimator, вызвав методFacerecService.createLiveness2DEstimator. В качестве аргумента укажите один из доступных файлов конфигурации:liveness_2d_estimator.xml– первая реализация, не рекомендуется к использованию (предназначена только для сохранения обратной совместимости)liveness_2d_estimator_v2.xml– ускоренная и улучшенная версия имеющегося модуля, рекомендуемый вариантliveness_2d_estimator_v3.xml– оценка с применением нескольких дополнительных проверок, например, присутствие лица в кадре, фронтальность лица и качество изображения.
Для получения результата оценки можно использовать два метода:
Liveness2DEstimator.estimateLivenessиLiveness2DEstimator.estimate.
Liveness2DEstimator.estimateLiveness: Этот метод возвращает объектLiveness2DEstimator.Liveness.Использование файлов конфигурации
liveness_2d_estimator.xmlиliveness_2d_estimator_v2.xmlпозволяет получить следующие результаты оценки:Liveness2DEstimator.Liveness.NOT_ENOUGH_DATA– недостаточно данных для принятия решенияLiveness2DEstimator.Liveness.REAL– наблюдаемое лицо принадлежит живому человекуLiveness2DEstimator.Liveness.FAKE– наблюдаемое лицо является фотографией
Использование файла конфигурации
liveness_2d_estimator_v3.xmlпозволяет получить расширенные результаты оценки:Liveness2DEstimator.Liveness.REAL- наблюдаемое лицо принадлежит живому человекуLiveness2DEstimator.Liveness.FAKE- наблюдаемое лицо является фотографиейLiveness2DEstimator.Liveness.IN_PROCESS- оценка liveness не может быть выполненаLiveness2DEstimator.Liveness.NO_FACES- отсутствие лиц на входном изображенииLiveness2DEstimator.Liveness.MANY_FACES- больше одного лица на входном изображенииLiveness2DEstimator.Liveness.FACE_OUT- наблюдаемое лицо выходит за границы входного изображенияLiveness2DEstimator.Liveness.FACE_TURNED_RIGHT- наблюдаемое лицо не расположено фронтально и повернуто вправоLiveness2DEstimator.Liveness.FACE_TURNED_LEFT- наблюдаемое лицо не расположено фронтально и повернуто влевоLiveness2DEstimator.Liveness.FACE_TURNED_UP- наблюдаемое лицо не расположено фронтально и направлено вверхLiveness2DEstimator.Liveness.FACE_TURNED_DOWN- наблюдаемое лицо не расположено фронтально и направлено внизLiveness2DEstimator.Liveness.BAD_IMAGE_LIGHTING- входное изображение снято в условиях плохого освещенияLiveness2DEstimator.Liveness.BAD_IMAGE_NOISE- высокий уровень зашумленности входного изображенияLiveness2DEstimator.Liveness.BAD_IMAGE_BLUR- высокий уровень размытости входного изображенияLiveness2DEstimator.Liveness.BAD_IMAGE_FLARE- большое число вспышек на входном изображении
Liveness2DEstimator.estimate: Этот метод возвращает объектLiveness2DEstimator.LivenessAndScore, содержащий следующие поля:liveness- объект класса/структурыLiveness2DEstimator.Liveness(см. выше).score– числовое значение в диапазоне от 0 до 1, выражающее вероятность принадлежности лица реальному человеку (дляliveness_2d_estimator.xmlтолько 0 или 1).
- C++
- C#
- Java
- Python
// создание объекта Liveness2DEstimator
std::vector<pbio::RawSample::Ptr> liveness_2d_estimator = service->createLiveness2DEstimator("liveness_2d_estimator_v2.xml");
// детекция лиц
std::vector<pbio::RawSample::Ptr> samples = capturer->capture(image);
for(size_t i = 0; i < samples.size(); ++i)
{
// оценка liveness
const pbio::Liveness2DEstimator::Liveness liveness = liveness_2d_estimator->estimateLiveness(*samples[i]);
}
// создание объекта Liveness2DEstimator
Liveness2DEstimator liveness_2d_estimator = service.createLiveness2DEstimator("liveness_2d_estimator_v2.xml");
// детекция лиц
List<RawSample> samples = capturer.capture(image);
for(int i = 0; i < samples.Count; ++i)
{
RawSample sample = samples[i];
// оценка liveness
Liveness2DEstimator.Liveness liveness = liveness_2d_estimator.estimateLiveness(sample);
}
// создание объекта Liveness2DEstimator
Liveness2DEstimator liveness_2d_estimator = service.createLiveness2DEstimator("liveness_2d_estimator_v2.xml");
// детекция лиц
Vector<RawSample> samples = capturer.capture(image);
for(int i = 0; i < samples.size(); i++)
{
RawSample sample = samples.get(i);
// оценка liveness
Liveness2DEstimator.Liveness liveness = liveness_2d_estimator.estimateLiveness(sample);
}
# создание объекта Liveness2DEstimator
liveness_estimator = service.create_liveness_2d_estimator("liveness_2d_estimator_v2.xml")
# детекция лиц
samples = capturer.capture(image)
for sample in samples:
# оценка liveness
liveness = liveness_estimator.estimate_liveness(sample)
Примеры использования доступны в сэмпле demo (C++/C#/Android).
Временные характеристики алгоритмов оценки живости (мс)
| Версия | Core i7 4.5 ГГц (1 ядро) | Google Pixel 3 |
| liveness_2d_estimator.xml | 250 | 126 (GPU) / 550 (CPU) |
| liveness_2d_estimator_v2.xml | 10 | 20 |
Точность алгоритмов оценки живости
| Набор данных | TAR@FAR=1e-2 |
| CASIA Face Anti-spoofing | 0.99 |
Активная (сценарная) проверка
Данный тип оценки живости требует от пользователя выполнения определенных действий (сценария), например, "повернуть голову", "моргнуть" и т.д. Проверка осуществляется через объект VideoWorker на основе видео потока. Более подробное описание представлено в разделе Обработка видеопотока.
FaceAttributesEstimator
Данный класс используется для оценки наличия маски на лице и оценки состояния глаз (открыты/закрыты). Для получения оценки необходимо вызвать метод FaceAttributesEstimator.estimate(RawSample). Результат оценки – объект Attribute, который содержит в себе следующие атрибуты:
score– вероятность наличия у лица требуемого атрибута, значение от0до1(если выставлено значение-1, то данное поле недоступно для заданного типа оценки)verdict– вероятность наличия у лица требуемого атрибута, логическое значение (true/false)mask– объект класса/структурыFaceAttributesEstimator.FaceAttributes.Attribute, который содержит в себе следующие значения:NOT_COMPUTED– оценка не производиласьNO_MASK– лицо без маскиHAS_MASK– лицо с маской
left_eye_state,right_eye_state– объекты класса/структурыFaceAttributesEstimator.FaceAttributes.EyeStateScore, которые содержат в себе следующие значения:NOT_COMPUTED– оценка не производиласьCLOSED– глаз закрытOPENED– глаз открыт
Детекция маски
Для проверки наличия маски на лице необходимо использовать FaceAttributesEstimator совместно с файлом конфигурации face_mask_estimator.xml. При этом в возвращаемом объекте Attribute выставляются атрибуты score, verdict и mask.
Улучшенный алгоритм проверки маски на лице доступен в файле конфигурации "face_mask_estimator_v2.xml" (на данный момент доступен только в 64-разрядной системе Windows x86 или 64-разрядной системе Linux x86).
- C++
- C#
- Java
- Python
// создание объекта FaceAttributesEstimator
const pbio::FaceAttributesEstimator::Ptr face_mask_estimator = service->createFaceAttributesEstimator("face_mask_estimator_v2.xml");
// детекция лиц
std::vector<pbio::RawSample::Ptr> samples = capturer->capture(image);
for(size_t i = 0; i < samples.size(); ++i)
{
// оценка наличия маски
const pbio::FaceAttributesEstimator::Attribute mask = face_mask_estimator->estimate(*samples[i]);
}
// создание объекта FaceAttributesEstimator
FaceAttributesEstimator face_mask_estimator = service.createFaceAttributesEstimator("face_mask_estimator_v2.xml");
// детекция лиц
List<RawSample> samples = capturer.capture(image);
for(int i = 0; i < samples.Count; ++i)
{
RawSample sample = samples[i];
// оценка наличия маски
FaceAttributesEstimator.Attribute mask = face_mask_estimator.estimate(sample);
}
// создание объекта FaceAttributesEstimator
FaceAttributesEstimator face_mask_estimator = service.createFaceAttributesEstimator("face_mask_estimator_v2.xml");
// детекция лиц
Vector<RawSample> samples = capturer.capture(image);
for(int i = 0; i < samples.size(); i++)
{
RawSample sample = samples.get(i);
// оценка наличия маски
FaceAttributesEstimator.Attribute mask = face_mask_estimator.estimate(sample);
}
# создание объекта FaceAttributesEstimator
face_mask_estimator = service.create_face_attributes_estimator("face_mask_estimator_v2.xml")
# детекция лиц
samples = capturer.capture(image)
for sample in samples:
# оценка наличия маски
mask = face_mask_estimator.estimate(sample)
Для оценки наличия маски на лице через API процессинг-блоков см. раздел Детекция маски.
Состояние глаз (открыты/закрыты)
Для проверки состояния глаз (открыты/закрыты) необходимо использовать FaceAttributesEstimator совместно с файлом конфигурации eyes_openness_estimator_v2.xml. В возвращаемом объекте Attribute выставляются атрибуты left_eye_state и right_eye_state.
- C++
- C#
- Java
- Python
// создание объекта FaceAttributesEstimator
const pbio::FaceAttributesEstimator::Ptr eyes_openness_estimator = service->createFaceAttributesEstimator("eyes_openness_estimator_v2.xml");
// детекция лиц
std::vector<pbio::RawSample::Ptr> samples = capturer->capture(image);
for(size_t i = 0; i < samples.size(); ++i)
{
// оценка состояния глаз
const pbio::FaceAttributesEstimator::Attribute eyes_state = eyes_openness_estimator->estimate(*samples[i]);
}
// создание объекта FaceAttributesEstimator
FaceAttributesEstimator eyes_openness_estimator = service.createFaceAttributesEstimator("eyes_openness_estimator_v2.xml");
// детекция лиц
List<RawSample> samples = capturer.capture(image);
for(int i = 0; i < samples.Count; ++i)
{
RawSample sample = samples[i];
// оценка состояния глаз
FaceAttributesEstimator.Attribute eyes_state = eyes_openness_estimator.estimate(sample);
}
// создание объекта FaceAttributesEstimator
FaceAttributesEstimator eyes_openness_estimator = service.createFaceAttributesEstimator("eyes_openness_estimator_v2.xml");
// детекция лиц
Vector<RawSample> samples = capturer.capture(image);
for(int i = 0; i < samples.size(); i++)
{
RawSample sample = samples.get(i);
// оценка состояния глаз
FaceAttributesEstimator.Attribute eyes_state = eyes_openness_estimator.estimate(sample);
}
# создание объекта FaceAttributesEstimator
eyes_openness_estimator = service.create_face_attributes_estimator("eyes_openness_estimator_v2.xml")
# детекция лиц
samples = capturer.capture(image)
for sample in samples:
# оценка состояния глаз
eyes_state = eyes_openness_estimator.estimate(sample)