Python口罩检测模型应用

作者: 浪漫矢志不渝 | 来源:发表于2021-12-08 11:09 被阅读0次

    研究人脸检测的时候,碰到口罩检测模型,觉得蛮有意思的就稍作分享下。

    主要代码(maskCheck.py):
    # -*- coding:utf-8 -*-
    import os
    import cv2
    import paddlehub as hub
    import matplotlib.image as im
    import matplotlib.pyplot as plt
    
    # 定义预测结果文件夹
    if not os.path.exists('./detection_result'):
        os.mkdir('./detection_result')
    
    # 遍历测试图片
    test_img_path = os.listdir('img')
    if test_img_path:
        length = len(test_img_path)
        for a in range(1, length + 1):
            test_img_path[a - 1] = './img/' + test_img_path[a - 1]
    
    # 遍历读取图片生成对象列表
    imgs = [[cv2.imread(image_path)] for image_path in test_img_path]
    for i in imgs:
        # 加载预测模型
        # module = hub.Module(name="pyramidbox_lite_mobile_mask")
        module = hub.Module(name="pyramidbox_lite_server_mask")
        # 口罩检测预测
        visualization = True  # 将预测结果保存图片可视化
        output_dir = 'detection_result'  # 预测结果图片保存在当前运行路径下detection_result文件夹下
        results = module.face_detection(images=i, use_multi_scale=True, shrink=0.6, visualization=True,
                                        output_dir='detection_result')
        for result in results:
            print(result)
    
    # 预测结果展示
    # 需要读取的路径
    path_name = r'./detection_result'
    
    for item in os.listdir(path=path_name):
        img = im.imread(os.path.join(path_name, item))
        plt.imshow(img)
        plt.show()
    

    img文件夹:存储待检测图片
    detection_result:存放检测结果图片
    上面代码基本的一些描述已经在代码中会做了标注,运行方式为python maskCheck.py
    对于两个模型检测出来的结果有些许不同(还有误差)。

    pyramidbox_lite_mobile_mask.png pyramidbox_lite_server_mask.png

    同时这里对module.face_detection的一些参数做说明:

    shrink

    该参数用于设置图片的缩放比例,输入值应位于区间 (0 ~ 1],默认为 0.5。shrink 值越大,则对于输入图片中的小尺寸人脸有更好的检测效果,反之则对于大尺寸人脸有更好的检测。同时,shrink 值越大,则模型计算成本越高。建议用户根据实际应用场景调整该值,尽可能使输入图像的人脸尺寸在缩放后分布于 8 ~ 130pix 之间。

    use_multi_scale

    该参数用于设置是否开启多尺度的人脸检测,默认为关闭。开启多尺度人脸检测能够更好的检测到输入图像中不同尺寸的人脸,但是会增加模型计算量,降低预测速度,建议在对人脸漏检要求比较低的场景下开启该设置。这两个关键参数接口的开放,可以满足很大一部分场景下的业务需求,迅速提升性能。

    最后,其实代码本身逻辑不怎么难懂,主要是应用开源模型来实现的,重点在于研究其处理方式,更有兴趣的,可以下载其模型研究(在使用时,已经下载到你本地路径了)。

    相关文章

      网友评论

        本文标题:Python口罩检测模型应用

        本文链接:https://www.haomeiwen.com/subject/jxxtfrtx.html