安装PaddleHub和模型

pip install paddlehub -i https://mirror.baidu.com/pypi/simple

hub install pyramidbox_lite_mobile_mask==1.3.0

模型概述:PyramidBox-Lite是基于2018年百度发表于计算机视觉顶级会议ECCV 2018的论文PyramidBox而研发的轻量级模型,模型基于主干网络FaceBoxes,对于光照、口罩遮挡、表情变化、尺度变化等常见问题具有很强的鲁棒性。该PaddleHub Module是针对于移动端优化过的模型,适合部署于移动端或者边缘检测等算力受限的设备上,并基于WIDER FACE数据集和百度自采人脸数据集进行训练,支持预测,可用于人脸检测。

口罩人脸检测

1. 单张图片检测

import matplotlib.pyplot as plt 
import paddlehub as hub
import os
import cv2

module = hub.Module(name="pyramidbox_lite_mobile_mask")

test_img_path = ["./1.jpg"]

img1 = cv2.imread(test_img_path[0],cv2.IMREAD_COLOR) 

# 展示待预测图片
cv2.imshow("src",img1)

imgs = [cv2.imread(test_img_path[0])]

# 口罩检测预测
# visualization=True 将预测结果保存图片可视化
# output_dir='detection_result' 预测结果图片保存在当前运行路径下detection_result文件夹下
results = module.face_detection(images=imgs, use_multi_scale=True, shrink=0.6, visualization=True, output_dir='./')
print(results)

# 预测结果展示
path = results[0]['path'].split(".")[0]+".jpg"
img2 = cv2.imread(path,cv2.IMREAD_COLOR)
cv2.imshow("dst",img2)

2. 视频流检测

import matplotlib.pyplot as plt 
import paddlehub as hub
import os
import cv2

module = hub.Module(name="pyramidbox_lite_mobile_mask")

cap = cv2.VideoCapture(0)
 
while (1):
    # 获取一帧图像
    ret, frame = cap.read()
    # 缩放并利用INTER_CUBIC插值法
    frame = cv2.resize(frame, (640, 480), interpolation=cv2.INTER_CUBIC)

    input_dict = {"data": [frame]}  
    result = module.face_detection(data=input_dict)

    print(result)
    
    # 绘制人脸框
    if len(result[0]['data']) != 0:
        for detection in result[0]['data']:
            confidence = float(detection['confidence'])
            # 获取左上角图片的坐标
            xmin = int(detection['left'])
            ymin = int(detection['top'])
            # 获取右下角图片的坐标
            xmax = int(detection['right'])
            ymax = int(detection['bottom'])
            if confidence > 0.5:
                # 图片 添加的文字 位置 字体 字体大小 字体颜q色 字体粗细
                cv2.putText(frame,detection['label'], (xmin, ymin + 20), cv2.FONT_HERSHEY_SIMPLEX, 0.75,
                           (0, 0, 255), 2)
                cv2.rectangle(frame, (xmin, ymin), (xmax, ymax), color=(0, 255, 0))
    # 展示图像
        cv2.imshow("capture", frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        # 每1毫秒监听一次键盘的动作,按q键结束,并保存图片
        cv2.imwrite('out.png', frame)
        print("已保存最后一帧!")
        break
# 关闭摄像头及显示窗口
cap.release()
cv2.destroyAllWindows()
print('人脸摄像头实时检测完成')

服务部署

PaddleHub Serving可以部署一个在线人脸关键点检测服务。

1. 启动PaddleHub Serving

hub serving start -m pyramidbox_lite_mobile_mask

这样就完成了一个人脸关键点服务化API的部署,默认端口号为8866。

NOTE: 如使用GPU预测,则需要在启动服务之前,请设置CUDA_VISIBLE_DEVICES环境变量,否则不用设置。

2. 发送预测请求

import requests
import json
import cv2
import base64
import time
 
# 格式转换
def cv2_to_base64(image):
    data = cv2.imencode('.jpg', image)[1]
    return base64.b64encode(data.tobytes()).decode('utf8')
 
# 向服务器发送请求
def predict(image):
    # 发送HTTP请求
    data = {'images':[cv2_to_base64(image)]}
    headers = {"Content-type": "application/json"}
    url = "http://127.0.0.1:8866/predict/pyramidbox_lite_mobile_mask" # ultra_light_fast_generic_face_detector_1mb_640
    r = requests.post(url=url, headers=headers, data=json.dumps(data))
    return r.json()["results"]
#[{'data': [{'bottom': 75, 'confidence': 0.9988584518432617, 'left': 167, 'right': 193, 'top': 40}], 'path': 'ndarray_time=1628745620275759.0'}]
 
print('开始人脸摄像头实时检测')
# 从摄像头中读取图像帧
 
cap = cv2.VideoCapture(0)
 
while (1):
    # 获取一帧图像
    ret, frame = cap.read()
    # 缩放并利用INTER_CUBIC插值法
    frame = cv2.resize(frame, (640, 480), interpolation=cv2.INTER_CUBIC)
    # fps计算
    start = time.time()
    result = predict(frame)
    end = time.time()
    fps = 1 / (end - start)
    # 绘制人脸框
    if len(result[0]['data']) != 0:
        for detection in result[0]['data']:
            confidence = float(detection['confidence'])
            # 获取左上角图片的坐标
            xmin = int(detection['left'])
            ymin = int(detection['top'])
            # 获取右下角图片的坐标
            xmax = int(detection['right'])
            ymax = int(detection['bottom'])
            if confidence > 0.7:
                # 图片 添加的文字 位置 字体 字体大小 字体颜q色 字体粗细
                cv2.putText(frame, detection['label'], (xmin, ymin + 20), cv2.FONT_HERSHEY_SIMPLEX, 0.75,
                           (0, 0, 255), 2)
                cv2.rectangle(frame, (xmin, ymin), (xmax, ymax), color=(0, 255, 0))
    # 展示图像
    cv2.putText(frame, 'fps:{:.2f}'.format(fps), (20, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 255), 2)
    cv2.imshow("capture", frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        # 每1毫秒监听一次键盘的动作,按q键结束,并保存图片
        cv2.imwrite('out.png', frame)
        print("已保存最后一帧!")
        break
# 关闭摄像头及显示窗口
cap.release()
cv2.destroyAllWindows()
print('人脸摄像头实时检测完成')

更多模型及使用方法参考官网:PaddleHub官网