设计思路
本次应用的Python库是cv2和dlib,主要运用了dlib自带的人脸检测器和dlib官网提供的人脸检测模型(shape_predictor_68_face_landmarks.dat)
具体步骤如下:
- 导入模型
- 读入图片
- 判断人脸个数并输出
- 进行人脸标记
实现代码
# !/usr/bin/env python
# —*— coding: utf-8 —*—
# @Time: 2020/1/3 14:42
# @Author: Martin
# @File: Face_Detection.py
# @Software:PyCharm
import cv2
import dlib
import numpy as np
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor('../res/shape_predictor_68_face_landmarks.dat')
img = cv2.imread('../res/test.jpg')
results = detector(img, 1)
if len(results) >= 1:
print("{} faces detected." .format(len(results)))
elif len(results) == 0:
print("No faces")
for i in range(len(results)):
landmarks = np.matrix([[p.x, p.y] for p in predictor(img, results[i]).parts()])
img = img.copy()
for idx, point in enumerate(landmarks):
pos = (point[0, 0], point[0, 1])
cv2.circle(img, pos, 1, color=(0, 255, 0))
cv2.namedWindow("img", 2)
cv2.imshow("img", img)
cv2.waitKey(0)
最终结果
总共检测到了15张人脸