利用cv2和dlib进行人脸检测与人脸标记

设计思路

本次应用的Python库是cv2和dlib,主要运用了dlib自带的人脸检测器和dlib官网提供的人脸检测模型(shape_predictor_68_face_landmarks.dat)
具体步骤如下:

  1. 导入模型
  2. 读入图片
  3. 判断人脸个数并输出
  4. 进行人脸标记

实现代码

# !/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张人脸

发布了102 篇原创文章 · 获赞 93 · 访问量 9650

猜你喜欢

转载自blog.csdn.net/Deep___Learning/article/details/103821175
今日推荐