文章目录

  • 效果展示
  • 数据集展示
  • 为人脸照片添加口罩代码
  • 掩膜生成代码

效果展示

数据集展示

数据集来源:使用了开源数据集FaceMask_CelebA

github地址:https://github.com/sevenHsu/FaceMask_CelebA.git

部分人脸数据集:

口罩样本数据集:

为人脸照片添加口罩代码

这部分有个库face_recognition需要安装,如果之前没有用过的小伙伴可能得费点功夫。
Face Recognition 库主要封装了dlib这一 C++ 图形库,通过 Python 语言将它封装为一个非常简单就可以实现人脸识别的 API 库,屏蔽了人脸识别的算法细节,大大降低了人脸识别功能的开发难度。

#!/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.dirname('E:/play/FaceMask_CelebA-master/facemask_image/')
WHITE_IMAGE_PATH = os.path.join(IMAGE_DIR, 'front_14.png')
BLUE_IMAGE_PATH = os.path.join(IMAGE_DIR, 'front_14.png')
SAVE_PATH = os.path.dirname('E:/play/FaceMask_CelebA-master/save/synthesis/')
SAVE_PATH2 = os.path.dirname('E:/play/FaceMask_CelebA-master/save/masks/')class FaceMasker:KEY_FACIAL_FEATURES = ('nose_bridge', 'chin')def __init__(self, face_path, mask_path, white_mask_path, save_path, save_path2, model='hog'):self.face_path = face_pathself.mask_path = mask_pathself.save_path = save_pathself.save_path2 = save_path2self.white_mask_path = white_mask_pathself.model = modelself._face_img: ImageFile = Noneself._black_face_img = Noneself._mask_img: ImageFile = Noneself._white_mask_img = Nonedef mask(self):import face_recognitionface_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)self._white_mask_img = Image.open(self.white_mask_path)self._black_face_img = Image.new('RGB', self._face_img.size, 0)found_face = Falsefor face_landmark in face_landmarks:# check whether facial features meet requirementskip = Falsefor facial_feature in self.KEY_FACIAL_FEATURES:if facial_feature not in face_landmark:skip = Truebreakif skip:continue# mask facefound_face = Trueself._mask_face(face_landmark)if found_face:# saveself._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 resizewidth = self._mask_img.widthheight = self._mask_img.heightwidth_ratio = 1.2new_height = int(np.linalg.norm(nose_v - chin_bottom_v))# leftmask_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))# rightmask_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 masksize = (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 maskangle = 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 locationcenter_x = (nose_point[0] + chin_bottom_point[0]) // 2center_y = (nose_point[1] + chin_bottom_point[1]) // 2offset = mask_img.width // 2 - mask_left_img.widthradian = angle * np.pi / 180box_x = center_x + int(offset * np.cos(radian)) - rotated_mask_img.width // 2box_y = center_y + int(offset * np.sin(radian)) - rotated_mask_img.height // 2# add maskself._face_img.paste(mask_img, (box_x, box_y), mask_img)# split mask and resizewidth = self._white_mask_img.widthheight = self._white_mask_img.heightwidth_ratio = 1.2new_height = int(np.linalg.norm(nose_v - chin_bottom_v))# leftmask_left_img = self._white_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))# rightmask_right_img = self._white_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 masksize = (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 maskangle = 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 locationcenter_x = (nose_point[0] + chin_bottom_point[0]) // 2center_y = (nose_point[1] + chin_bottom_point[1]) // 2offset = mask_img.width // 2 - mask_left_img.widthradian = angle * np.pi / 180box_x = center_x + int(offset * np.cos(radian)) - rotated_mask_img.width // 2box_y = center_y + int(offset * np.sin(radian)) - rotated_mask_img.height // 2# add maskself._black_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 = self.save_path + '/' + os.path.basename(self.face_path) + '-with-mask' + path_splits[1]# new_face_path2 = self.save_path2 + '/' + os.path.basename(self.face_path) + '-binary' + path_splits[1]new_face_path = self.save_path + '/' + os.path.basename(self.face_path) + '-with-mask' + path_splits[1]new_face_path2 = self.save_path2 + '/'  + os.path.basename(self.face_path) + '-binary' + path_splits[1]self._face_img.save(new_face_path)self._black_face_img.save(new_face_path2)#         print(f'Save to {new_face_path}')@staticmethoddef 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)# FaceMasker("/home/aistudio/data/人脸.png", WHITE_IMAGE_PATH, True, 'hog').mask()from pathlib import Pathimages = Path("E:/play/FaceMask_CelebA-master/bbox_align_celeba").glob("*")
cnt = 0
for image in images:if cnt < 1:cnt += 1continueFaceMasker(image, BLUE_IMAGE_PATH, WHITE_IMAGE_PATH, SAVE_PATH, SAVE_PATH2, 'hog').mask()cnt += 1print(f"正在处理第{cnt}张图片,还有{99 - cnt}张图片")

掩膜生成代码

这部分其实就是对使用的口罩样本的二值化,因为后续要相关模型会用到

import os
from PIL import Image# 源目录
# MyPath = 'E:/play/FaceMask_CelebA-master/facemask_image/'
MyPath = 'E:/play/FaceMask_CelebA-master/save/masks/'
# 输出目录
OutPath = 'E:/play/FaceMask_CelebA-master/save/Binarization/'def processImage(filesoure, destsoure, name, imgtype):'''filesoure是存放待转换图片的目录destsoure是存在输出转换后图片的目录name是文件名imgtype是文件类型'''imgtype = 'bmp' if imgtype == '.bmp' else 'png'# 打开图片im = Image.open(filesoure + name)# =============================================================================#     #缩放比例#     rate =max(im.size[0]/640.0 if im.size[0] > 60 else 0, im.size[1]/1136.0 if im.size[1] > 1136 else 0)#     if rate:#         im.thumbnail((im.size[0]/rate, im.size[1]/rate))# =============================================================================img = im.convert("RGBA")pixdata = img.load()# 二值化for y in range(img.size[1]):for x in range(img.size[0]):if pixdata[x, y][0] < 90:pixdata[x, y] = (0, 0, 0, 255)for y in range(img.size[1]):for x in range(img.size[0]):if pixdata[x, y][1] < 136:pixdata[x, y] = (0, 0, 0, 255)for y in range(img.size[1]):for x in range(img.size[0]):if pixdata[x, y][2] > 0:pixdata[x, y] = (255, 255, 255, 255)img.save(destsoure + name, imgtype)def run():# 切换到源目录,遍历源目录下所有图片os.chdir(MyPath)for i in os.listdir(os.getcwd()):# 检查后缀postfix = os.path.splitext(i)[1]name = os.path.splitext(i)[0]name2 = name.split('.')if name2[1] == 'jpg-binary' or name2[1] == 'png-binary':processImage(MyPath, OutPath, i, postfix)if __name__ == '__main__':run()

Python实战——为人脸照片添加口罩相关推荐

  1. 20行Python代码检测人脸是否佩戴口罩

    最近,口罩成为绝对热门的话题,在疫情之下,出门不戴口罩不仅对自己不负责,对他人而言也是一种潜在的威胁.所以许多小区都有保安在门口守着,谁要是不戴口罩就吼回去(吓死我了). 很多人学习python,不知 ...

  2. 给人脸戴上口罩,Python实战项目来了

    大家好,人生苦短,我用Python.今天给大家分享一个Python 实战案例:为人脸照片添加口罩,喜欢本文记得收藏.点赞.关注. 废话不多说,我们先展示最终的效果. [注]完整版代码.资料,技术沟通, ...

  3. 实战:使用OpenCV+Python+dlib为人脸生成口罩

    点击上方"小白学视觉",选择加"星标"或"置顶" 重磅干货,第一时间送达本文转自|AI算法与图像处理 本文使用OpenCV dlib库生成口 ...

  4. 人脸口罩识别——人脸添加口罩方法masked_faces

    文章目录: 1 人脸添加口罩masked_faces 2 添加口罩原理 3 添加口罩代码操作 4 源码分析 A realistic approach to generate masked faces ...

  5. python 提取最小外接矩形_python给人脸带上口罩(简单版)

    导读 因为目前公开的口罩人脸数据比较少,如果想训练一个口罩人脸识别模型,必须依赖大量的人脸数据.为了收集到更多的口罩人脸数据,我们只能利用已有的公开人脸数据上通过程序来模拟人脸带口罩.这篇文章向大家介 ...

  6. 视频教程-YOLOv4目标检测实战:人脸口罩佩戴检测-计算机视觉

    YOLOv4目标检测实战:人脸口罩佩戴检测 大学教授,美国归国博士.博士生导师:人工智能公司专家顾问:长期从事人工智能.物联网.大数据研究:已发表学术论文100多篇,授权发明专利10多项 白勇 ¥88 ...

  7. 视频教程-Windows版YOLOv4目标检测实战:人脸口罩佩戴检测-计算机视觉

    Windows版YOLOv4目标检测实战:人脸口罩佩戴检测 大学教授,美国归国博士.博士生导师:人工智能公司专家顾问:长期从事人工智能.物联网.大数据研究:已发表学术论文100多篇,授权发明专利10多 ...

  8. python给人脸带上口罩(简单版)

    导读 因为目前公开的口罩人脸数据比较少,如果想训练一个口罩人脸识别模型,必须依赖大量的人脸数据.为了收集到更多的口罩人脸数据,我们只能利用已有的公开人脸数据上通过程序来模拟人脸带口罩.这篇文章向大家介 ...

  9. python ui自动化配置文件,python UI自动化实战记录八:添加配置

    添加配置文件写入测试地址等,当环境切换时只需修改配置文件即可. 1 在项目目录下添加文件 config.ini 写入: [Domain] domain = http://test.domain.cn ...

  10. Python简单实现人脸识别检测, 对照片进行评分

    大家好,今天和大家说说如何用Python简单实现人脸识别检测, 对照片进行排名,看看自己有多漂亮. [开发环境]: Python 3.8 Pycharm 2021.2 [模块使用]: requests ...

最新文章

  1. mysql没有makefile_make: *** 没有指明目标并且找不到 makefile。 停止。 make: ***
  2. QQ卖手办,用AI分析用户评论
  3. kazoo源码分析:Zookeeper客户端start概述
  4. 物联网改变生活——飞思卡尔技术论坛中国站侧记
  5. Asp.net(C#)-彩色图片转化为黑白
  6. springboot 添加允许跨域_springboot设置cors跨域请求的两种方式
  7. 看懂 IPv6+,这篇就够了
  8. Lua 如何快速的读取一个文件
  9. Android 用代码获取基站号(cell)和小区号(lac)
  10. Flask - Jinjia2
  11. 河北单招2021计算机类,2021河北省单招十大类专业
  12. JAVA计算机毕业设计博雅楼自习室预约系统Mybatis+系统+数据库+调试部署
  13. 计算机职称photoshop,职称计算机考试photoshop核心通关技巧
  14. Greasy Fork、GitHub、OpenUserJS
  15. 51单片机汇编密码锁(可修改密码,课程设计,含论文)!(大三上)
  16. android蓝牙python,android – 使用SL4A(Python)和蓝牙
  17. python爬虫有多少种方式_python爬虫-----Python访问http的几种方式
  18. 支付宝小程序获取位置API没有城市区号的最佳处理方案
  19. 关联任天堂账号与服务器断开,任天堂疑似遇安全漏洞 多名NS玩家表示账户异常登录!...
  20. Serial Presence Detect (SPD) Table

热门文章

  1. 医生- 患者 - 图标
  2. WCF服务启动时遇到AddressAccessDeniedException
  3. 在ashx文件中使用Session
  4. MATLAB教程(一)matlib介绍
  5. android解析html新闻的方法,Android使用Jsoup解析Html表格的方法
  6. opencv各种小程序代码
  7. Pyqt之QApplication
  8. Qt_QFileInfo几个路径函数的区别
  9. Java-密钥keytool及KeyStore的使用
  10. mongodb java 不等于_mongoDB在java上面的应用