face-mask人脸自动加口罩工具

本文应用场景在于疫情期间复工后,检查员工口罩佩戴情况,基于这个安排给我尽可能生成各种角度的戴口罩的人脸图片,还有就是针对百度搜索中人脸关键字段的图片爬取。

本文先简单介绍一下第一个部分的工作,就是测试face-mask的效果,简单介绍一下face-mask是基于dlib和face_recognition两大人脸检测的库实现的人脸关键点检测的方法,由于我远程办公的情况所以就只能在自己的windows笔记本上进行环境的配置,而在配置环境的过程中就不可避免的遇到了dlib库怎么都配置不上,因为face_recognition是依赖于dllib的所以我就开启了探索研究如何在windows+py3.7+dlib的环境配置道路。终于在查阅多篇博客之后最后基于扶封的博客(感谢博主:),需要的同学点击链接即可开启配置dlib之路),得到了配置的方法。

dlib配置好了我们就开始按照要求来配置face-mask的环境了,建议使用pip指令下载,如下:

pip install face-mask

理论上在配置完dlib之后应该是顺风顺水,就可以愉快的跑测试代码了。

代码的主题部分在face_mask文件夹的__main__.py里,其中默认的口罩模板存放路径如下

在代码目录下的face文件夹放入图片就OK了,最后识别人脸和给人脸加口罩的代码如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : 2014Vee
import os
import numpy as np
from PIL import Image, ImageFile

__version__ = '0.3.0'


IMAGE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'images')
DEFAULT_IMAGE_PATH = os.path.join(IMAGE_DIR, 'default-mask.png')
BLACK_IMAGE_PATH = os.path.join(IMAGE_DIR, 'black-mask.png')
BLUE_IMAGE_PATH = os.path.join(IMAGE_DIR, 'blue-mask.png')
RED_IMAGE_PATH = os.path.join(IMAGE_DIR, 'red-mask.png')


class FaceMasker:
    KEY_FACIAL_FEATURES = ('nose_bridge', 'chin')

    def __init__(self, face_path, mask_path, show=False, model='hog'):
        self.face_path = face_path
        self.mask_path = mask_path
        self.show = show
        self.model = model
        self._face_img: ImageFile = None
        self._mask_img: ImageFile = None

    def mask(self):
        import face_recognition

        face_image_np = face_recognition.load_image_file(self.face_path)
        face_locations = face_recognition.face_locations(face_image_np, model=self.model)
        face_landmarks = face_recognition.face_landmarks(face_image_np, face_locations)
        self._face_img = Image.fromarray(face_image_np)
        self._mask_img = Image.open(self.mask_path)

        found_face = False
        for face_landmark in face_landmarks:
            # check whether facial features meet requirement
            skip = False
            for facial_feature in self.KEY_FACIAL_FEATURES:
                if facial_feature not in face_landmark:
                    skip = True
                    break
            if skip:
                continue

            # mask face
            found_face = True
            self._mask_face(face_landmark)

        if found_face:
            if self.show:
                self._face_img.show()

            # save
            self._save()
        else:
            print('Found no face.')

    def _mask_face(self, face_landmark: dict):
        nose_bridge = face_landmark['nose_bridge']
        nose_point = nose_bridge[len(nose_bridge) * 1 // 4]
        nose_v = np.array(nose_point)

        chin = face_landmark['chin']
        chin_len = len(chin)
        chin_bottom_point = chin[chin_len // 2]
        chin_bottom_v = np.array(chin_bottom_point)
        chin_left_point = chin[chin_len // 8]
        chin_right_point = chin[chin_len * 7 // 8]

        # split mask and resize
        width = self._mask_img.width
        height = self._mask_img.height
        width_ratio = 1.2
        new_height = int(np.linalg.norm(nose_v - chin_bottom_v))

        # left
        mask_left_img = self._mask_img.crop((0, 0, width // 2, height))
        mask_left_width = self.get_distance_from_point_to_line(chin_left_point, nose_point, chin_bottom_point)
        mask_left_width = int(mask_left_width * width_ratio)
        mask_left_img = mask_left_img.resize((mask_left_width, new_height))

        # right
        mask_right_img = self._mask_img.crop((width // 2, 0, width, height))
        mask_right_width = self.get_distance_from_point_to_line(chin_right_point, nose_point, chin_bottom_point)
        mask_right_width = int(mask_right_width * width_ratio)
        mask_right_img = mask_right_img.resize((mask_right_width, new_height))

        # merge mask
        size = (mask_left_img.width + mask_right_img.width, new_height)
        mask_img = Image.new('RGBA', size)
        mask_img.paste(mask_left_img, (0, 0), mask_left_img)
        mask_img.paste(mask_right_img, (mask_left_img.width, 0), mask_right_img)

        # rotate mask
        angle = np.arctan2(chin_bottom_point[1] - nose_point[1], chin_bottom_point[0] - nose_point[0])
        rotated_mask_img = mask_img.rotate(angle, expand=True)

        # calculate mask location
        center_x = (nose_point[0] + chin_bottom_point[0]) // 2
        center_y = (nose_point[1] + chin_bottom_point[1]) // 2

        offset = mask_img.width // 2 - mask_left_img.width
        radian = angle * np.pi / 180
        box_x = center_x + int(offset * np.cos(radian)) - rotated_mask_img.width // 2
        box_y = center_y + int(offset * np.sin(radian)) - rotated_mask_img.height // 2

        # add mask
        self._face_img.paste(mask_img, (box_x, box_y), mask_img)

    def _save(self):
        path_splits = os.path.splitext(self.face_path)
        new_face_path = path_splits[0] + '-with-mask' + path_splits[1]
        self._face_img.save(new_face_path)
        print(f'Save to {new_face_path}')

    @staticmethod
    def get_distance_from_point_to_line(point, line_point1, line_point2):
        distance = np.abs((line_point2[1] - line_point1[1]) * point[0] +
                          (line_point1[0] - line_point2[0]) * point[1] +
                          (line_point2[0] - line_point1[0]) * line_point1[1] +
                          (line_point1[1] - line_point2[1]) * line_point1[0]) / \
                   np.sqrt((line_point2[1] - line_point1[1]) * (line_point2[1] - line_point1[1]) +
                           (line_point1[0] - line_point2[0]) * (line_point1[0] - line_point2[0]))
        return int(distance)


if __name__ == '__main__':
    FaceMasker("./face/1.jpg", DEFAULT_IMAGE_PATH, True, 'hog').mask()


 

  • 2
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 13
    评论
rfb-face-mask.pth 是一个文件路径,其中“rfb-face-mask”代表文件的名称,“.pth”代表文件的后缀。 这个文件很可能是一个神经网络模型的权重文件,用于实现人脸口罩检测。“rfb”可能是一种特定的神经网络架构,它通常用于目标检测任务。 人脸口罩检测是一种应用于人脸识别技术的衍生任务。由于全球的公共卫生危机,人们普遍开始佩戴口罩。因此,开发一种能够准确识别佩戴口罩人脸识别系统变得尤为重要。 这个文件可能是通过使用大量带有和不带有口罩人脸图像进行训练而生成的。训练神经网络需要大量的计算资源和时间,以使其能够从输入图像中准确地检测出人脸以及是否佩戴口罩。这样的模型可以应用于实时人脸识别系统中,以检测佩戴者是否佩戴口罩。 在应用人脸口罩检测系统时,我们可以使用这个.pth文件载训练好的模型权重,将其应用于实时图像或视频上。该模型能够迅速地检测图像中的人脸,并识别它们是否佩戴口罩。这样的模型可以应用于公共场所、交通枢纽和其他需要识别佩戴口罩情况的区域。 总之,rfb-face-mask.pth 文件很可能是一个神经网络模型的权重文件,用于实现人脸口罩检测任务。它可以帮助我们识别图像中的人脸,并准确判断他们是否佩戴口罩,从而提高公共卫生安全的水平。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值