人脸识别1——一个简单的人脸识别例子

 

1、dlib库的安装和shape_predictor_68_face_landmarks.dat的下载。

参考:
Python库之dlib库的简介、安装、使用方法详细攻略
我用的第三个方法:

在这里下载的只要三个记分
下载如下图这个文件
人脸识别1——一个简单的人脸识别例子_人脸识别
然后在这个文件目录下,运行 pip install dlib-19.6.1-cp36-cp36m-win_amd64.whl即可。

2、人脸识别代码——检测一张图片
#!Anaconda/anaconda/python
#coding: utf-8

"""
时间:2019年11月25日
shape_predictor_68_face_landmarks.dat,这是一个人脸68个特征点检测的数据库
代码功能:从图片中识别人脸,并实时标出面部特征点
"""

import dlib                     #人脸识别的库dlib
import cv2                      #图像处理的库OpenCv

# 与人脸检测相同,使用dlib自带的frontal_face_detector作为人脸检测器
detector = dlib.get_frontal_face_detector()

# 使用官方提供的模型构建特征提取器
predictor = dlib.shape_predictor('E:/python_project/face_recognition/home/shape_predictor_68_face_landmarks.dat')
# cv2读取图片
img = cv2.imread("E:\\python_project\\face_recognition\\face\\2.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 与人脸检测程序相同,使用detector进行人脸检测 dets为返回的结果
dets = detector(gray, 1)
# 使用enumerate 函数遍历序列中的元素以及它们的下标
# 下标k即为人脸序号
# left:人脸左边距离图片左边界的距离 ;right:人脸右边距离图片左边界的距离
# top:人脸上边距离图片上边界的距离 ;bottom:人脸下边距离图片上边界的距离
if len(dets) != 0:
    for k, d in enumerate(dets):
        print("dets{}".format(d))
        print("Detection {}: Left: {} Top: {} Right: {} Bottom: {}".format(
            k, d.left(), d.top(), d.right(), d.bottom()))

        # 使用predictor进行人脸关键点识别 shape为返回的结果
        shape = predictor(img, d)
        # 获取第一个和第二个点的坐标(相对于图片而不是框出来的人脸)
        print("Part 0: {}, Part 1: {} ...".format(shape.part(0), shape.part(1)))

        # 计算矩形框大小 / compute the size of rectangle box
        height = (d.bottom() - d.top())
        width = (d.right() - d.left())
        hh = int(height / 2)
        ww = int(width / 2)
        # 设置颜色 / the color of rectangle of faces detected
        color_rectangle = (0, 255, 255)
        # 绘制矩形框
        cv2.rectangle(img,
                      tuple([d.left() - ww, d.top() - hh]),
                      tuple([d.right() + ww, d.bottom() + hh]),
                      color_rectangle, 4)
        str(len(dets))
        print(len(dets))
        # 绘制特征点
        for index, pt in enumerate(shape.parts()):
            print('Part {}: {}'.format(index, pt))
            pt_pos = (pt.x, pt.y)
            cv2.circle(img, pt_pos, 1, (0, 255, 0), 1)
            # 利用cv2.putText输出1-68
            #font = cv2.FONT_HERSHEY_SIMPLEX
            #cv2.putText(img, str(index + 1), pt_pos, font, 0.3, (0, 0, 255), 1, cv2.LINE_AA)
cv2.namedWindow('img', 0)
cv2.imshow('img', img)
k = cv2.waitKey()
cv2.destroyAllWindows()


效果图
人脸识别1——一个简单的人脸识别例子_人脸识别_02

 

 

更多文章请关注《万象专栏》