一时对人脸识别发生了兴趣,这几天踩了不少坑,主要坑是在dlib的安装和参考网上代码时遇到或多或少代码错误。网上关于人脸检测、识别的代码很多,我采用了其中之一的方法,并综合应用,适合初学者入门学习,欢迎交流。
应用环境:window 7 、python3.5
shape_predictor_68_face_landmarks.dat 需在网上下载
dlib_face_recognition_resnet_model_v1.dat 需在网上下载
import dlib
import matplotlib.pyplot as plt
import numpy as np
import math,cv2
import os, glob,math
from skimage import io
def resize(image, width=1200): # 将待检测的image进行resize
r = width * 1.0 / image.shape[1]
dim = (width, int(image.shape[0] * r))
resized = cv2.resize(image, dim, interpolation=cv2.INTER_AREA)
return resized
def shape_to_np(shape, dtype="int"): # 将包含68个特征的的shape转换为numpy array格式
coords = np.zeros((68, 2), dtype=dtype)
for i in range(0, 68):
coords[i] = (shape.part(i).x, shape.part(i).y)
return coords
"""
人脸特征点检测
"""
def rect_to_bb(rect): # 获得人脸矩形的坐标信息
x = rect.left()
y = rect.top()
w = rect.right() - x
h = rect.bottom() - y
return (x, y, w, h)
"""
人脸对齐
"""
def face_alignment(faces):
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat") # 用来预测关键点
faces_aligned = []
for face in fa