目录
PaddleHub人脸检测示例
ultra_light_fast_generic_face_detector_1mb_640
本示例利用Ultra-Light-Fast-Generic-Face-Detector-1MB模型完成人脸检测。Ultra-Light-Fast-Generic-Face-Detector-1MB是针对边缘计算设备或低算力设备(如用ARM推理)设计的实时超轻量级通用人脸检测模型,可以在低算力设备中如用ARM进行实时的通用场景的人脸检测推理。该PaddleHub Module的预训练数据集为WIDER FACE数据集,可支持预测,在预测时会将图片输入缩放为640 * 480。
NOTE: 如果您在本地运行该项目示例,需要首先安装PaddleHub。如果您在线运行,需要首先fork该项目示例。之后按照该示例操作即可。
ultra_light_fast_generic_face_detector_1mb_640
模型链接:https://www.paddlepaddle.org.cn/hubdetail?name=ultra_light_fast_generic_face_detector_1mb_640&en_category=FaceDetection
环境:PaddlePaddle2.0.0rc PaddleHub2.0.0b1 ultra_light_fast_generic_face_detector_1mb_640 1.1.2(最新版)
一、安装新版Hub
!pip install paddlehub==2.0.0b1 -i https://pypi.tuna.tsinghua.edu.cn/simple
二、定义数据集
以本示例中文件夹下test_face_detection.jpg为待预测图片
实现效果
# 待检测照片
image = 'test_face_detection.jpg'
三、API预测
PaddleHub对于支持一键预测的module,可以调用module的相应预测API,完成预测功能。
def face_detection(images=None,
paths=None,
batch_size=1,
use_gpu=False,
visualization=False,
output_dir=None,
confs_threshold=0.5):
检测输入图片中的所有人脸位置
参数
- images (list[numpy.ndarray]): 图片数据,ndarray.shape 为 [H, W, C],BGR格式;
- paths (list[str]): 图片的路径;
- batch_size (int): batch 的大小;
- use_gpu (bool): 是否使用 GPU;
- visualization (bool): 是否将识别结果保存为图片文件;
- output_dir (str): 图片的保存路径,当为 None 时,默认设为face_detector_640_predict_output;
- confs_threshold (float): 置信度的阈值。
返回
- res (list[dict]): 识别结果的列表,列表中每一个元素为 dict,关键字有 path, save_path, data,其中:
- path 字段为原输入图片的路径(仅当使用paths输入时存在);
- save_path 字段为可视化图片的保存路径(仅当visualization=True时存在);
- data 字段为检测结果,类型为list,list的每一个元素为dict,其中’left’, ‘right’, ‘top’, ‘bottom’ 为人脸识别框,‘confidence’ 为此识别框置信度。
四、加载预训练模型并预测
Ultra-Light-Fast-Generic-Face-Detector-1MB提供了两种预训练模型,ultra_light_fast_generic_face_detector_1mb_320和ultra_light_fast_generic_face_detector_1mb_640。
- ultra_light_fast_generic_face_detector_1mb_320,在预测时会将图片输入缩放为320 * 240,预测速度更快。关于该模型更多介绍, 查看PaddleHub官网介绍
- ultra_light_fast_generic_face_detector_1mb_640,在预测时会将图片输入缩放为640 * 480,预测精度更高。关于该模型更多介绍, 查看PaddleHub官网介绍
用户根据需要,选择具体模型。利用PaddleHub使用该模型时,只需更改指定name,即可实现无缝切换。
import paddlehub as hub
import cv2
face_detector = hub.Module(name="ultra_light_fast_generic_face_detector_1mb_640")
result = face_detector.face_detection(images=[cv2.imread(image)],visualization=True)
print(result[0]['save_path'])
# or
# result = face_detector.face_detection((paths=['/PATH/TO/IMAGE'])
五、命令行预测
!hub run ultra_light_fast_generic_face_detector_1mb_640 --input_path "test_face_detection.jpg" --output_dir 'face_detector_640_predict_output' --visualization True
六、效果展示
预测结果展示
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
test_img_path = result[0][‘save_path’]
img = mpimg.imread(test_img_path)
plt.figure(figsize=(10,10))
plt.imshow(img)
plt.axis(‘off’)
plt.show()