insightface 基于 PaddlePaddle 的 BlazeFace 人脸检测实战:训练、WIDER-FACE 评估与部署全流程解析
2026/9/10 11:28:24 网站建设 项目流程

insightface 基于 PaddlePaddle 的 BlazeFace 人脸检测实战:训练、WIDER-FACE 评估与部署全流程解析

【免费下载链接】insightfaceState-of-the-art 2D and 3D Face Analysis Project项目地址: https://gitcode.com/GitHub_Trending/in/insightface

Arcface-Paddle 是基于 PaddlePaddle 实现的深度人脸检测与识别工具集,本文聚焦其中的人脸检测模块:基于 PaddleDetection 开发的BlazeFace-FPN-SSH检测器。读完本文,你将掌握从 WIDER-FACE 数据集准备、训练配置、mAP 评估、模型导出到 PaddleInference 部署的完整技术链路,并理解BlazeNet/BlazeNeck配置与test_blazeface.py的源码级推理实现。本文内容以仓库文档 detection/blazeface_paddle/README_cn.md 为主体,并结合 detection/blazeface_paddle/test_blazeface.py 源码进行纵深佐证。

1. 模块定位:Arcface-Paddle 中的检测部分

Arcface-Paddle是开源的深度人脸检测、识别工具,目前提供三个预训练模型:用于人脸检测的BlazeFace、用于人脸识别的ArcFaceMobileFace。其中:

  • 本部分(人脸检测)基于PaddleDetection进行开发,位于仓库 detection/blazeface_paddle 目录;
  • 人脸识别(ArcFace/MobileFace 的训练、评估、导出)相关内容,参见 recognition/arcface_paddle/README_cn.md;
  • 基于 PaddleInference 的 Whl 包预测部署可作为检测→识别全流程的后续环节。

仓库内与本文直接相关的核心资源包括:

资源路径作用
中文文档detection/blazeface_paddle/README_cn.md训练/评估/部署完整指南
英文文档detection/blazeface_paddle/README_en.md同上(英文版)
检测 Demo 脚本detection/blazeface_paddle/test_blazeface.py基于 PaddleInference 的端到端人脸检测示例
安装文档recognition/arcface_paddle/install_cn.mdPaddlePaddle 与 PaddleDetection 环境安装
识别模块recognition/arcface_paddle/README_cn.md检测后的识别下游任务

2. 模型库与 WIDER-FACE 基准性能

文档给出了两个检测模型在 WIDER-FACE 数据集上的 mAP 与预测时延对比(多尺度评估得到 Easy/Medium/Hard Set 上的 mAP):

网络结构输入尺寸图片个数/GPUepoch 数量Easy/Medium/Hard SetCPU 预测时延GPU 预测时延模型大小(MB)
BlazeFace-FPN-SSH640810000.9187 / 0.8979 / 0.816831.7ms5.6ms0.646
RetinaFace480x640--- / - / 0.8250182.0ms17.4ms1.680

关于该基准表的几个关键说明(引用自原文档):

  • mAP 通过多尺度评估策略获得,具体流程见本文第 7 节"在 WIDER-FACE 数据集上评估";
  • 测速分辨率为640×640,CPU 环境为 Intel(R) Xeon(R) Gold 6148 CPU @ 2.40GHz,CPU 线程数设置为 5,详见本文第 9 节"推理速度提升";
  • RetinaFace的速度测试代码参考自仓库 detection/retinaface/README.md;
  • 测试环境为:CPU Intel(R) Xeon(R) Gold 6184 CPU @ 2.40GHz,GPU 为单张 NVIDIA Tesla V100。

可以看到,BlazeFace-FPN-SSH相比 RetinaFace 在模型体积(0.646MB vs 1.680MB)与推理速度上优势明显(CPU 31.7ms vs 182.0ms,GPU 5.6ms vs 17.4ms),而在 Hard Set 上 mAP 为 0.8168,略低于 RetinaFace 的 0.8250,适合对实时性与轻量化有要求的场景。

3. 环境安装

人脸检测模块的运行需要PaddlePaddle 2.2.0rc0 或更高版本以及PaddleDetection。详细安装步骤请参考 recognition/arcface_paddle/install_cn.md,核心要点如下。

3.1 环境要求

  • Python 3.x
  • CUDA >= 10.1(使用 paddlepaddle-gpu 时)
  • cuDNN >= 7.6.4(使用 paddlepaddle-gpu 时)
  • NCCL >= 2.1.2(使用分布式训练/评估时)
  • gcc >= 8.2

3.2 安装 PaddlePaddle

推荐使用 Docker 环境(paddlepaddle/paddle:2.2.0rc0或 GPU 版本paddlepaddle/paddle:2.2.0rc0-gpu-cuda11.2-cudnn8,创建容器时建议设置--shm-size=8G);也可通过 pip 直接安装:

# GPU 版本 pip3 install paddlepaddle-gpu==2.2.0rc0 --upgrade -i https://mirror.baidu.com/pypi/simple # CPU 版本 pip3 install paddlepaddle==2.2.0rc0 --upgrade -i https://mirror.baidu.com/pypi/simple

安装后可用以下命令验证:

import paddle paddle.utils.run_check()
python3 -c "import paddle; print(paddle.__version__)"

注意:若先安装 CPU 版本再切换 GPU 版本,需先卸载 CPU 版本,避免版本混乱;从源码编译时需打开WITH_DISTRIBUTE=ON编译选项以支持分布式训练。

3.3 安装 PaddleDetection

cd <path/to/clone/PaddleDetection> git clone <PaddleDetection 仓库地址> cd PaddleDetection pip3 install -r requirements.txt

提示:若只使用识别模块可跳过 PaddleDetection 的安装;若只使用检测模块则可跳过识别模块的依赖安装。

4. 数据准备:WIDER-FACE 数据集

训练与测试使用 WIDER-FACE 数据集。PaddleDetection 加载wider_face类型数据集的目录结构如下:

dataset/wider_face/ ├── wider_face_split │ ├── wider_face_train_bbx_gt.txt │ ├── wider_face_val_bbx_gt.txt ├── WIDER_train │ ├── images │ │ ├── 0--Parade │ │ │ ├── 0_Parade_marchingband_1_100.jpg │ │ │ ├── 0_Parade_marchingband_1_381.jpg │ │ │ │ ... │ │ ├── 10--People_Marching │ │ │ ... ├── WIDER_val │ ├── images │ │ ├── 0--Parade │ │ │ ├── 0_Parade_marchingband_1_1004.jpg │ │ │ ├── 0_Parade_marchingband_1_1045.jpg │ │ │ │ ... │ │ ├── 10--People_Marching │ │ │ ...

其中wider_face_split目录下的 txt 文件为标注文件(训练/验证框标注),WIDER_trainWIDER_val为图像目录。手动下载数据集时,可在对应目录下执行:

cd dataset/wider_face && ./download_wider_face.sh

5. 参数配置:blazeface_fpn_ssh_1000e.yml

训练使用configs/face_detection/blazeface_fpn_ssh_1000e.yml配置(该配置文件位于 PaddleDetection 仓库的configs/face_detection/下),其摘要如下:

_BASE_: [ '../datasets/wider_face.yml', '../runtime.yml', '_base_/optimizer_1000e.yml', '_base_/blazeface_fpn.yml', '_base_/face_reader.yml', ] weights: output/blazeface_fpn_ssh_1000e/model_final multi_scale_eval: True

该配置通过_BASE_继承并组合了 5 个依赖文件,各文件职责如下:

配置文件主要说明
wider_face.yml训练数据和验证数据的路径
runtime.yml公共运行参数,如是否使用 GPU、每多少个 epoch 存储 checkpoint 等
optimizer_1000e.yml学习率与优化器配置
blazeface_fpn.yml模型与主干网络(backbone)结构
face_reader.yml数据读取器配置,如 batch size、并发加载子进程数,以及读取后的预处理操作(resize、数据增强等)

实际使用时可根据自身情况修改上述文件,例如数据集路径、batch size 等。

5.1 BlazeNet 与 BlazeNeck 结构配置

基础模型的配置参考configs/face_detection/_base_/blazeface.yml;改进模型在 backbone 之后增加了FPNSSH的 neck 结构,配置文件参考configs/face_detection/_base_/blazeface_fpn.yml,可根据需求配置,具体如下:

BlazeNet: blaze_filters: [[24, 24], [24, 24], [24, 48, 2], [48, 48], [48, 48]] double_blaze_filters: [[48, 24, 96, 2], [96, 24, 96], [96, 24, 96], [96, 24, 96, 2], [96, 24, 96], [96, 24, 96]] act: hard_swish # 配置backbone中BlazeBlock的激活函数,基础模型为relu,增加FPN和SSH时需使用hard_swish BlazeNeck: neck_type : fpn_ssh # 可选only_fpn、only_ssh和fpn_ssh in_channel: [96,96]

参数解读:

  • blaze_filters:BlazeBlock 各阶段的卷积核通道数,2表示该阶段进行 stride=2 的下采样;
  • double_blaze_filters:DoubleBlazeBlock 的通道配置,形式为[输入通道, 中间通道, 输出通道, 步长]
  • act: hard_swish:BlazeBlock 激活函数。基础模型为 relu,但增加 FPN 和 SSH 时必须改用 hard_swish
  • neck_type:可选项为only_fpnonly_sshfpn_ssh,本模型采用fpn_ssh
  • in_channel: [96, 96]:neck 的输入通道数。

6. 模型训练

6.1 下载预训练权重

训练前先下载 BlazeNet 预训练模型:

wget https://paddledet.bj.bcebos.com/models/pretrained/blazenet_pretrain.pdparams

6.2 单卡 / 多卡训练

PaddleDetection 提供单卡与多卡两种训练模式:

  • GPU 单卡训练
export CUDA_VISIBLE_DEVICES=0 # windows和Mac下不需要执行该命令 python tools/train.py -c configs/face_detection/blazeface_fpn_ssh_1000e.yml -o pretrain_weight=blazenet_pretrain
  • GPU 多卡训练
export CUDA_VISIBLE_DEVICES=0,1,2,3 # windows和Mac下不需要执行该命令 python -m paddle.distributed.launch --gpus 0,1,2,3 tools/train.py -c configs/face_detection/blazeface_fpn_ssh_1000e.yml -o pretrain_weight=blazenet_pretrain
  • 中断恢复训练:日常训练中若因故中断,可使用-r参数从指定 checkpoint 恢复:
export CUDA_VISIBLE_DEVICES=0 # windows和Mac下不需要执行该命令 python tools/train.py -c configs/face_detection/blazeface_fpn_ssh_1000e.yml -r output/blazeface_fan_ssh_1000e/100

6.3 训练策略

BlazeFace的训练策略为:每卡batch_size=32,在4 张 GPU上训练(总batch_size为 128),学习率0.002,共训练1000 epoch

注意:人脸检测模型目前不支持边训练边评估

7. 在 WIDER-FACE 数据集上评估

步骤一:评估并生成结果文件

python -u tools/eval.py -c configs/face_detection/blazeface_fpn_ssh_1000e.yml \ -o weights=output/blazeface_fpn_ssh_1000e/model_final \ multi_scale_eval=True BBoxPostProcess.nms.score_threshold=0.1

设置multi_scale_eval=True进行多尺度评估。评估完成后,将在output/pred中生成 txt 格式的测试结果。

步骤二:下载官方评估脚本与 Ground Truth 文件

wget http://mmlab.ie.cuhk.edu.hk/projects/WIDERFace/support/eval_script/eval_tools.zip unzip eval_tools.zip && rm -f eval_tools.zip

步骤三:开始评估

方法一:Python 评估

git clone <WiderFace-Evaluation 仓库地址> cd WiderFace-Evaluation # 编译 python3 setup.py build_ext --inplace # 开始评估 python3 evaluation.py -p /path/to/PaddleDetection/output/pred -g /path/to/eval_tools/ground_truth

方法二:MatLab 评估

eval_tools/wider_eval.m中修改保存结果路径和绘制曲线的名称:

pred_dir = './pred'; legend_name = 'Paddle-BlazeFace';

wider_eval.m是评估模块的主要执行程序,运行命令如下:

matlab -nodesktop -nosplash -nojvm -r "run wider_eval.m;quit;"

8. 推理部署:模型导出与 PaddleInference

8.1 导出部署模型

训练过程中保存的模型同时包含前向预测与反向传播过程,而工业部署不需要反向传播,因此需要将模型导出为部署格式。PaddleDetection 提供tools/export_model.py脚本:

python tools/export_model.py -c configs/face_detection/blazeface_fpn_ssh_1000e.yml --output_dir=./inference_model \ -o weights=output/blazeface_fpn_ssh_1000e/best_model BBoxPostProcess.nms.score_threshold=0.1

预测模型会导出到inference_model/blazeface_fpn_ssh_1000e目录下,包含 4 个文件:

  • infer_cfg.yml(推理配置)
  • model.pdiparams(权重参数)
  • model.pdiparams.info(参数信息)
  • model.pdmodel(网络结构)

若不指定--output_dir,模型默认导出在output_inference

这里将 NMS 后处理的score_threshold修改为 0.1:在 mAP 基本不受影响的前提下,GPU 预测速度可大幅提升。

8.2 使用 PaddleInference 部署

PaddleDetection 提供 PaddleInference、PaddleServing、PaddleLite 等多种部署形式,支持服务端、移动端、嵌入式等平台,并提供完善的 Python 与 C++ 部署方案。以 Python 为例:

python deploy/python/infer.py --model_dir=./inference_model/blazeface_fpn_ssh_1000e --image_file=demo/road554.png --use_gpu=True

infer.py提供了丰富的接口,支持接入视频文件、摄像头进行预测。

9. 推理速度提升

9.1 复现官方测速指标

若要复现文档给出的速度指标,需要修改预测模型配置文件./inference_model/blazeface_fpn_ssh_1000e/infer_cfg.yml中的输入尺寸(即 Preprocess 部分):

mode: fluid draw_threshold: 0.5 metric: WiderFace arch: Face min_subgraph_size: 3 Preprocess: - is_scale: false mean: - 123 - 117 - 104 std: - 127.502231 - 127.502231 - 127.502231 type: NormalizeImage - interp: 1 keep_ratio: false target_size: - 640 - 640 type: Resize - type: Permute label_list: - face

该配置对应文档基准测试采用的640×640输入、均值[123, 117, 104]、方差127.502231的归一化方案。注意:infer_cfg.yml中的归一化参数(mean/std 为 BGR 通道顺序)与 test_blazeface.py 中normalize_image使用的 ImageNet 风格参数(scale=1/255、mean=[0.485,0.456,0.406]、std=[0.229,0.224,0.225],RGB 顺序)不同——前者是 PaddleDetection 导出配置,后者是仓库自带 demo 脚本的推理管线,两者属于不同部署链路,使用时需保持一致。

9.2 CPU 环境启用 MKLDNN 加速

如果希望模型在 CPU 环境下更快推理,可安装带 MKL-DNN 的 paddlepaddle wheel 包并开启 mkldnn 加速:

# 使用GPU测速: python deploy/python/infer.py --model_dir=./inference_model/blazeface_fpn_ssh_1000e --image_dir=./path/images --run_benchmark=True --use_gpu=True # 使用cpu测速: # 下载paddle whl包 wget <paddlepaddle-cpu-mkl whl 包地址> # 安装 pip install paddlepaddle-0.0.0-cp37-cp37m-linux_x86_64.whl # 推理 python deploy/python/infer.py --model_dir=./inference_model/blazeface_fpn_ssh_1000e --image_dir=./path/images --enable_mkldnn=True --run_benchmark=True --cpu_threads=5

--cpu_threads=5即文档基准测试中的线程设置(CPU 线程数 5),用于复现 31.7ms 的 CPU 时延指标。

10. 人脸检测 Demo 与源码级实现解析

仓库自带的 detection/blazeface_paddle/test_blazeface.py 是基于 PaddleInference 的端到端人脸检测示例,无需自行下载训练权重——脚本会在首次运行时自动下载 BlazeFace 推理模型到~/.insightface/ppmodels/目录。

10.1 运行示例

先下载待检测图像与用于可视化绘制中文标签的字体文件:

# 下载用于人脸检测的示例图像 wget <示例图像地址> # 下载字体,用于可视化 wget <SourceHanSansCN-Medium.otf 字体地址>

然后执行检测:

python3.7 test_blazeface.py --input=friends1.jpg --output="./output"

最终可视化结果(人脸框 + 置信度标注)保存在output目录下。

10.2 命令行参数(来自源码)

test_blazeface.py通过argparse提供如下参数(见 test_blazeface.py):

参数默认值说明
--det_modelBlazeFace检测模型名称,支持BlazeFace/ArcFace/MobileFace,也可指定包含inference.pdmodelinference.pdiparams的本地目录
--use_gpuTrue是否使用 GPU 预测
--enable_mkldnnTrue是否启用 MKLDNN 加速,仅在--use_gpu=False时生效
--cpu_threads1CPU 线程数,仅在--use_gpu=False时生效
--input必填待预测的图像路径/图像目录/视频(.mp4)路径
--output./output/预测结果保存目录
--det_thresh0.8检测后处理阈值

10.3 源码级推理链路

从源码结构看,脚本的推理实现可以分为以下几个层次(可结合 test_blazeface.py 对应类核对):

  • 模型自动下载check_model_file(L114-L171)维护model_mapBlazeFaceblazeface_fpn_ssh_1000e_v1.0_infer),缺失时从BASE_DOWNLOAD_URL下载 tar 包并解压出inference.pdmodelinference.pdiparamsinference.pdiparams.info三个文件;
  • PaddleInference 配置BasePredictor.load_predictor(L374-L400)创建paddle.inference.Config,GPU 模式调用enable_use_gpu(200, 0)并开启 IR 优化;CPU 模式调用disable_gpu()set_cpu_math_library_num_threads,启用 MKLDNN 时设置 10 个 shape 的缓存容量;统一开启内存优化(enable_memory_optim)与 zero-copy(switch_use_feed_fetch_ops(False));
  • 预处理Detector.preprocess(L419-L440)将图像 resize 到640×640(与 infer_cfg.yml 的 target_size 一致),按scale=1/255、mean/std 归一化后转 CHW,并记录im_shapescale_factor
  • 后处理Detector.postprocess(L442-L444)按det_thresh(默认 0.8)过滤检测框,保留score > thresh的框;
  • 输入/输出ImageReader/VideoReader支持单图、目录批量图像与.mp4视频;ImageWriter/VideoWriter负责结果写出,FaceDetector.draw使用下载的思源黑体字体在框上绘制"face 0.98xx"形式的标签与置信度。

由于FaceDetectorpredict方法以生成器形式逐帧 yield{"box_list", "features", "labels"},因此该脚本既可作为独立 CLI 工具运行,也可以被上层代码(如人脸识别、特征库检索)以 Python 接口方式复用,与 Arcface-Paddle 的识别链路形成闭环。

11. 参考文献

@misc{long2020ppyolo, title={PP-YOLO: An Effective and Efficient Implementation of Object Detector}, author={Xiang Long and Kaipeng Deng and Guanzhong Wang and Yang Zhang and Qingqing Dang and Yuan Gao and Hui Shen and Jianguo Ren and Shumin Han and Errui Ding and Shilei Wen}, year={2020}, eprint={2007.12099}, archivePrefix={arXiv}, primaryClass={cs.CV} } @misc{ppdet2019, title={PaddleDetection, Object detection and instance segmentation toolkit based on PaddlePaddle.}, author={PaddlePaddle Authors}, howpublished = {\url{https://github.com/PaddlePaddle/PaddleDetection}}, year={2019} } @article{bazarevsky2019blazeface, title={BlazeFace: Sub-millisecond Neural Face Detection on Mobile GPUs}, author={Valentin Bazarevsky and Yury Kartynnik and Andrey Vakunov and Karthik Raveendran and Matthias Grundmann}, year={2019}, eprint={1907.05047}, archivePrefix={arXiv} }

【免费下载链接】insightfaceState-of-the-art 2D and 3D Face Analysis Project项目地址: https://gitcode.com/GitHub_Trending/in/insightface

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询