实战:使用OpenCV+Python+dlib为人脸生成口罩
点击上方“小白学视觉”,选择加"星标"或“置顶”
重磅干货,第一时间送达
本文转自|AI算法与图像处理
![](https://filescdn.proginn.com/399e795f1f3e8dec4d51bc8e51dda9e7/04ffcab95c2b2b09c9f03c12f2c9dcb9.webp)
![](https://filescdn.proginn.com/2f7c6ea13d37d0a5a2d08e469f283086/0df7141e30f93a13f88d45ce4c1b0e41.webp)
安装所需的软件包
#requirements_facemask.txt
numpy == 1.18.5
pip == 20.2.2
imutils == 0.5.3
python >=3.7
dlib == 19.21.0
cmake == 3.18.0
opencv-python == 4.4.0
导入库
# 必要的导入
import cv2
import dlib
import numpy as np
import os
import imutils
# 设置目录
os.chdir('PATH_TO_DIR')
path = 'IMAGE_PATH'
# 初始化颜色 [color_type] = (Blue, Green, Red)
color_blue = (239,207,137)
color_cyan = (255,200,0)
color_black = (0, 0, 0)
图像预处理
# 加载图像并调整大小,将其转换为灰度
img= cv2.imread('image_path')
img = imutils.resize(img, width = 500)
gray=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
使用dlib、OpenCV和Python检测和提取人脸关键点
![](https://filescdn.proginn.com/254aa873711cf544f508f63675bc4d65/a36b020ffbcef58b3ac09a56ac65585d.webp)
人脸关键点检测被定义为检测脸上的关键标志点并跟踪它们(对由于头部运动和面部表情而导致的刚性和非刚性面部变形具有鲁棒性)[来源]
什么是人脸关键点?
定位图像中检测到的人脸。 面部关键点的检测
鼻子 下颚线 左眼和右眼 左右眉 嘴
![](https://filescdn.proginn.com/f17c27206faf7a5e355d20631fcbed3e/3ff9c201d0e2588a36742fefbda72d6c.webp)
左眼:点[42,47] 嘴:点[48,67] 左眉:点[22,26] 鼻子:点[27,34] 右眉:点[17,21] 右眼:点[36,41] 下颚线:点[0,16]
人脸检测与人脸关键点检测
# 初始化dlib的人脸检测器
detector = dlib.get_frontal_face_detector()
"""
在灰度图像中检测人脸并创建一个对象-存储边界矩形的坐标列表
第二个参数中的“1”表示应该向上采样图像1次。
这会使图像变得更大,并允许我们检测更多的面孔
"""
faces = detector(gray, 1)
# 打印边界矩形的坐标
print(faces)
print("Number of faces detected: ", len(faces))
"""
# 使用for循环来提取特定坐标(x1,x2,y1,y2)
for face in faces:
x1 = face.left()
y1 = face.top()
x2 = face.right()
y2 = face.bottom()
# 在检测到的脸部周围画一个矩形
cv2.rectangle(img, (x1,y1), (x2,y2),(0,255,0),3)
cv2.imshow("image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
"""
# 文件路径
p = "shape_predictor_68_face_landmarks.dat"
# 初始化dlib的预测器
predictor = dlib.shape_predictor(p)
# 使用预测器获取外形
for face in faces:
landmarks = predictor(gray, face)
# for n in range(0,68):
# x = landmarks.part(n).x
# y = landmarks.part(n).y
# img_landmark = cv2.circle(img, (x, y), 4, (0, 0, 255), -1)
Dlib口罩方法
![](https://filescdn.proginn.com/a753d103bedfc0c5da6dd3149a7c8487/10a4f69e72de6d6c148bfa98328f161b.webp)
![](https://filescdn.proginn.com/981d4169aa43f1d4b25d7c8641ef1909/1fb78c963cd4418f93e45c104b6b4f5f.webp)
points = []
for i in range(1, 16):
point = [landmarks.part(i).x, landmarks.part(i).y]
points.append(point)
# print(points)
# 宽,高覆盖口罩
mask_a = [((landmarks.part(42).x), (landmarks.part(15).y)),
((landmarks.part(27).x), (landmarks.part(27).y)),
((landmarks.part(39).x), (landmarks.part(1).y))]
# 宽,中覆盖口罩
mask_c = [((landmarks.part(29).x), (landmarks.part(29).y))]
# 宽、低覆盖口罩
mask_e = [((landmarks.part(35).x), (landmarks.part(35).y)),
((landmarks.part(34).x), (landmarks.part(34).y)),
((landmarks.part(33).x), (landmarks.part(33).y)),
((landmarks.part(32).x), (landmarks.part(32).y)),
((landmarks.part(31).x), (landmarks.part(31).y))]
fmask_a = points + mask_a
fmask_c = points + mask_c
fmask_e = points + mask_e
# mask_type = {1: fmask_a, 2: fmask_c, 3: fmask_e}
# mask_type[choice2]
# 使用Python OpenCV - cv2.polylines()方法为[mask_type]绘制口罩轮廓:
# fmask_a = wide, high coverage mask,
# fmask_c = wide, medium coverage mask,
# fmask_e = wide, low coverage mask
fmask_a = np.array(fmask_a, dtype=np.int32)
fmask_c = np.array(fmask_c, dtype=np.int32)
fmask_e = np.array(fmask_e, dtype=np.int32)
mask_type = {1: fmask_a, 2: fmask_c, 3: fmask_e}
mask_type[choice2]
# 更改参数[mask_type]和color_type用于各种组合
img2 = cv2.polylines(img, [mask_type[choice2]], True, choice1, thickness=2, lineType=cv2.LINE_8)
# 使用Python OpenCV - cv2.fillPoly()方法填充口罩
# 更改参数[mask_type]和color_type用于各种组合
img3 = cv2.fillPoly(img2, [mask_type[choice2]], choice1, lineType=cv2.LINE_AA)
# cv2.imshow("image with mask outline", img2)
cv2.imshow("image with mask", img3)
# 为测试保存输出文件
outputNameofImage = "output/imagetest.jpg"
print("Saving output image to", outputNameofImage)
cv2.imwrite(outputNameofImage, img3)
points = []
for i in range(1, 16):
point = [landmarks.part(i).x, landmarks.part(i).y]
points.append(point)
# print(points)
# 椭圆参数为高,圆形是覆盖口罩
top_ellipse = landmarks.part(27).y + (landmarks.part(28).y - landmarks.part(27).y) / 2
centre_x = landmarks.part(28).x
centre_y = landmarks.part(8).y - ((landmarks.part(8).y - (top_ellipse)) / 2)
# 椭圆高度
axis_major = (landmarks.part(8).y - top_ellipse) / 2
# 椭圆宽度
axis_minor = ((landmarks.part(13).x - landmarks.part(3).x) * 0.8) / 2
centre_x = int(round(centre_x))
centre_y = int(round(centre_y))
axis_major = int(round(axis_major))
axis_minor = int(round(axis_minor))
centre = (centre_x, centre_y)
axes = (axis_major, axis_minor)
# 使用Python OpenCV - cv2.ellipse()方法绘制口罩轮廓
# 更改最后一个参数- line thickness和color_type为各种组合
img_2 = cv2.ellipse(img, centre, axes, 0, 0, 360, color_type, thickness=2)
# 使用Python OpenCV - cv2.ellipse()方法绘制口罩轮廓
# 更改最后一个参数-line thickness为负数用于填充,color_type用于各种组合
img_3 = cv2.ellipse(img, centre, axes, 0, 0, 360, color_type, thickness=-1)
# cv2.imshow("image with mask outline", img_2)
cv2.imshow("image with mask", img_3)
# 使用input()函数根据用户需求获取口罩类型和口罩颜色
choice1 = input("Please select the choice of mask color\nEnter 1 for blue\nEnter 2 for black:\n")
choice1 = int(choice1)
if choice1 == 1:
choice1 = color_blue
print('You selected mask color = blue')
elif choice1 == 2:
choice1 = color_black
print('You selected mask color = black')
else:
print("invalid selection, please select again.")
input("Please select the choice of mask color\nEnter 1 for blue\nEnter 2 for black :\n")
choice2 = input("Please enter choice of mask type coverage \nEnter 1 for high \nEnter 2 for medium \nEnter 3 for low :\n")
choice2 = int(choice2)
if choice2 == 1:
# choice2 = fmask_a
print(f'You chosen wide, high coverage mask')
elif choice2 == 2:
# choice2 = fmask_c
print(f'You chosen wide, medium coverage mask')
elif choice2 == 3:
# choice2 = fmask_e
print(f'You chosen wide, low coverage mask')
else:
print("invalid selection, please select again.")
input("Please enter choice of mask type coverage \nEnter 1 for high \nEnter 2 for medium \nEnter 3 for low :\n")
# print(choice2)
结果
![](https://filescdn.proginn.com/226c53f1c9c2ec8b2cf580a05d4dd0de/32f5bbc896be7e7e868a522d3150ab28.webp)
![](https://filescdn.proginn.com/cd33e2013c153a35697fe5268e8d3b84/00ebbfe227a4d62884c451573fff5a70.webp)
![](https://filescdn.proginn.com/a8a5c53ef9924b2970183950f36eccf2/49fce47f5526ad25cffa7ee0e87c7f51.webp)
![](https://filescdn.proginn.com/af8f6237df39fc04f1e12859f5af03ff/8f0ce23c75e2acee4c5e2401c99949ef.webp)
![](https://filescdn.proginn.com/c2d6e47877c898eeaa8bca3c434ac028/4ccd28a7bd2042e00201950ec7c4d565.webp)
![](https://filescdn.proginn.com/6bbffe6243688feff981e48bbaa5cbad/36c364e6625603c0d6c8e00db715e999.webp)
![](https://filescdn.proginn.com/fc57e6bc91f9713bac8a1d6b5d1492ca/482405dfec55fc42a4d8acd472679da3.webp)
![](https://filescdn.proginn.com/a38779b1ec04811dfe835545b1870639/694d4b3e2ad77c89ac283a4196403eec.webp)
![](https://filescdn.proginn.com/7be5ff44f488cb9061d5afe19825b5e1/46d29814e09932fe3e1b25cc7ffce26f.webp)
![](https://filescdn.proginn.com/ee5b2cffd099b1bd7cd46874a910515d/db323f1797f8dfbfc2980d6e100c235a.webp)
![](https://filescdn.proginn.com/a7f5935f3b159b4e02b0567aa8272b22/01bf9ce4db60cbec611f27ae974a5e9a.webp)
![](https://filescdn.proginn.com/61a8ef4e3c46e44b635ea52c6d1121c1/96a3132ac240a072f3d520c656050652.webp)
![](https://filescdn.proginn.com/658896ed33e748253889aeec5e6913bf/1f6c843af633072f106bd7675084e950.webp)
![](https://filescdn.proginn.com/17cb40061eb8cbc455f3b899d596bade/524f18be549e0441b4d4dc3452e497a9.webp)
![](https://filescdn.proginn.com/dbfbd57fcb9e7e49e4954654f96294d8/dd0515a265b699dd45d219280fa8f643.webp)
![](https://filescdn.proginn.com/6a9a742e8dbf91aafc308c93043dc69d/84533c77c2e13cfb751e3be259c2f54c.webp)
![](https://filescdn.proginn.com/b0f1721fbc0c5eadbb410b51be573809/8f4869edd835827c789ff037e8a489e9.webp)
![](https://filescdn.proginn.com/02d18bc952428bc65951fecd40a3034b/0e2d491eabc69669465a265106c3b9b8.webp)
结论
参考文献:
Facial landmarks with dlib, OpenCV, and Python(https://www.pyimagesearch.com/2017/04/03/facial-landmarks-dlib-opencv-python/) Facial point annotations(https://ibug.doc.ic.ac.uk/resources/facial-point-annotations/) Real-Time Face Pose Estimation(http://blog.dlib.net/2014/08/real-time-face-pose-estimation.html) Drawing Functions in OpenCV(https://docs.opencv.org/master/dc/da5/tutorial_py_drawing_functions.html) Sources of images — open source and https://www.kaggle.com/dansbecker/5-celebrity-faces-dataset
交流群
欢迎加入公众号读者群一起和同行交流,目前有SLAM、三维视觉、传感器、自动驾驶、计算摄影、检测、分割、识别、医学影像、GAN、算法竞赛等微信群(以后会逐渐细分),请扫描下面微信号加群,备注:”昵称+学校/公司+研究方向“,例如:”张三 + 上海交大 + 视觉SLAM“。请按照格式备注,否则不予通过。添加成功后会根据研究方向邀请进入相关微信群。请勿在群内发送广告,否则会请出群,谢谢理解~
评论