一时对人脸识别发生了兴趣,这几天踩了不少坑,主要坑是在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 iodef resize(image, width=1200):  # 将待检测的image进行resizer = width * 1.0 / image.shape[1]dim = (width, int(image.shape[0] * r))resized = cv2.resize(image, dim, interpolation=cv2.INTER_AREA)return resizeddef 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() - xh = rect.bottom() - yreturn (x, y, w, h)"""
人脸对齐
"""
def face_alignment(faces):predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat") # 用来预测关键点faces_aligned = []for face in faces:rec = dlib.rectangle(0,0,face.shape[0],face.shape[1])shape = predictor(np.uint8(face),rec) # 注意输入的必须是uint8类型order = [36,45,30,48,54] # left eye, right eye, nose, left mouth, right mouth  注意关键点的顺序,这个在网上可以找for j in order:x = shape.part(j).xy = shape.part(j).y#cv2.circle(face, (x, y), 2, (0, 0, 255), -1)    #测试加还是不加eye_center =((shape.part(36).x + shape.part(45).x) * 1./2, # 计算两眼的中心坐标(shape.part(36).y + shape.part(45).y) * 1./2)dx = (shape.part(45).x - shape.part(36).x) # note: right - rightdy = (shape.part(45).y - shape.part(36).y)angle = math.atan2(dy,dx) * 180. / math.pi # 计算角度RotateMatrix = cv2.getRotationMatrix2D(eye_center, angle, scale=1) # 计算仿射矩阵RotImg = cv2.warpAffine(face, RotateMatrix, (face.shape[0], face.shape[1])) # 进行放射变换,即旋转faces_aligned.append(RotImg)return faces_aligneddef feature(path,foces):im_raw =cv2.imread(foces).astype('uint8')   detector = dlib.get_frontal_face_detector()gray = cv2.cvtColor(im_raw, cv2.COLOR_BGR2GRAY)rects = detector(gray, 1)src_faces = []for (i, rect) in enumerate(rects):(x, y, w, h) = rect_to_bb(rect)detect_face = im_raw[y:y+h,x:x+w]src_faces.append(detect_face)cv2.rectangle(im_raw, (x, y), (x + w, y + h), (0, 255, 0), 2)cv2.putText(im_raw, "Face: {}".format(i + 1), (x - 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)faces_aligned = face_alignment(src_faces)#cv2.imshow("src", im_raw)    for j in os.listdir(path):                 #清空拟装合影照片中分离人脸目录中的文件os.remove(path+'\\'+j)         i = 0for face in faces_aligned:#cv2.imshow("det_{}".format(i), face)i = i + 1        io.imsave(path+'\\'+'Face{}.jpg'.format(i),face)cv2.imshow("Output", im_raw)cv2.waitKey(0)def predict(descriptors,path):# 对需识别的人脸进行同样处理# 提取描述子img = io.imread(path)dets = detector(img, 1)dist = []for k, d in enumerate(dets):shape = sp(img, d)face_descriptor = facerec.compute_face_descriptor(img, shape)# 转换为numpy arrayd_test = np.array(face_descriptor)# 计算欧式距离for i in descriptors:dist_ = np.linalg.norm(i-d_test)dist.append(dist_)return distdef create_face_space( faces_folder_path ):# 对文件夹下的每一个人脸进行:# 1.人脸检测# 2.关键点检测# 3.描述子提取# 已知人脸描述子listdescriptors = []for f in glob.glob(os.path.join(faces_folder_path, "*.jpg")):#print("Processing file: {}".format(f))img = io.imread(f)# 1.已知人脸检测dets = detector(img, 1)#print("Number of faces detected: {}".format(len(dets)))for k, d in enumerate(dets):# 2.关键点检测shape = sp(img, d)# 3.提取描述子,128D向量face_descriptor = facerec.compute_face_descriptor(img, shape)# 转换为numpy arrayv = np.array(face_descriptor)descriptors.append(v)return descriptorsdef demo(path,faces_folder_path):global detector, sp, facerec# 加载正脸检测器detector = dlib.get_frontal_face_detector()# 加载人脸关键点检测器sp = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")# 3. 加载人脸识别模型facerec = dlib.face_recognition_model_v1("dlib_face_recognition_resnet_model_v1.dat") descriptors = create_face_space(faces_folder_path)# 存放在已知人脸目录中的照片对应的人员名单candidate = ['刘德华','巩俐','范冰冰','奥巴马','张文']for f in glob.glob(os.path.join(path, "*.jpg")):dist = predict(descriptors, f)#print(dist)# 候选人和距离组成一个dictc_d = dict(zip(candidate, dist))cd_sorted = sorted(c_d.items(), key=lambda d:d[1])#print( cd_sorted )     if  len(cd_sorted) !=0 and cd_sorted[0][1]<0.6: #比对值,越小越准确但会有已知人认不出print ("此人_{} 是: ".format(f),cd_sorted[0][0])           else:print ("不知此人_{} 是谁: ".format(f))
if __name__ == "__main__":foces=r'C:\Users\Administrator\Desktop\123.jpg'   #合影照片path = r'examples\test'          #暂存合影照片中分离人脸的子目录faces_folder_path =r'examples\trains' #已知人脸的子目录feature(path,foces)demo(path, faces_folder_path)

python--合影照片中多人脸检测、分离、存储、识别综合应用相关推荐

  1. python+opencv+dlib实现人脸检测与表情识别

    python+opencv+dlib实现人脸检测与表情识别 一,dlib简单介绍:Dlib包含广泛的机器学习算法.所有的设计都是高度模块化的,快速执行,并且通过一个干净而现代的C ++ API,使用起 ...

  2. python 人脸检测_借助摄像头在Python中实现人脸检测

    Python部落(www.freelycode.com)组织翻译, 禁止转载 本文作者是Shantnu Tiwari--曾多年在C/C++的魔爪中饱受折磨,直到他发现了Python--使用起来感觉如呼 ...

  3. Python实现摄像头实时人脸检测

    摄像头中的人脸检测,也是人脸识别的一部分, 摄像头播放的画面本质上是按帧将图片拼凑起来的, 有图片的话,获取图片的中人脸呢再上一篇中我们已经涉及了 想要进行人脸识别, 我们需要OpenCV, 还是先来 ...

  4. opencv中的人脸检测案例

    案例:人脸检测 利用OpenCV中自己已经训练好的检测器 1 检测流程 1.读取图片,并转换为灰度图像 2.实例化人脸和眼睛检测的分类器对象 # 实例化级联分类器 face_cas = cv.Casc ...

  5. android 人脸检测 facedec,智能访客系统中的人脸检测及方向判别算法.pdf

    智能访客系统中的人脸检测及方向判别算法,人脸识别算法,人脸检测算法,opencv人脸识别算法,人脸识别算法有哪些,人脸识别pca算法,人脸比对算法,android人脸识别算法,adaboost人脸检测 ...

  6. 十三.人脸检测和车牌识别

    人脸检测和车牌识别 1. 人脸检测 首先我们要搞清楚人脸检测中的一些概念. 人脸检测: 在一张图像中判断是否存在人脸并找出人脸所在的位置 人脸识别: 在人脸检测的基础上收集人脸数据集合进行处理保存信息 ...

  7. 高帧率扑克牌识别技术详解一(可用于车牌识别,字符识别,人脸检测,验证码识别等等成熟领域)

    分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow 也欢迎大家转载本篇文章.分享知识,造福人民,实现我们中华民族伟大复兴! 高帧率扑 ...

  8. 如何用OpenCV在Python中实现人脸检测

    选自towardsdatascience 作者:Maël Fabien 机器之心编译 参与:高璇.张倩.淑婷 本教程将介绍如何使用 OpenCV 和 Dlib 在 Python 中创建和运行人脸检测算 ...

  9. 使用网络摄像头在 Python 中进行人脸检测

    本教程是Python 中的人脸识别的后续教程,因此请确保您已经阅读了第一篇文章. 正如第一篇文章中提到的,通过网络摄像头从检测图像中的人脸到检测视频中的人脸非常容易--这正是我们将在本文中详细介绍的内 ...

最新文章

  1. SPICE:过程改进的又一种选择
  2. 从工程转向管理,访谈Github公司的Phil Haack
  3. jQuery操作DOM元素案例
  4. 智能家居制作之WiFi遥控家中设备
  5. linux 线程池编程,Linux-C-9-线程池编程
  6. python等待用户输入指定秒_如何在10秒后强制用户输入
  7. 【转载】Deferred Shading
  8. Web CAD SDK 14.1.0 New Crack
  9. Oracle 12c PDB数据库的基本操作积累
  10. VMware虚拟机net模式无法共享主机ip
  11. 如何让ie窗口显示到最前面
  12. python动作识别库_教你快速使用OpenCV/Python/dlib进行眨眼检测识别!
  13. JZOJ 1403.渡河
  14. 使用腾讯OCR进行文字识别
  15. 天猫登录html代码,天猫静态页面
  16. 基于Pytorch源码对SGD、momentum、Nesterov学习
  17. ChatGPT中GPT三个字母到底是什么意思
  18. Everyone Piano v2.2.10.16 WiN 电脑键盘钢琴模拟软件
  19. Supervisor安装、管理守护进程
  20. 2016再见,hello 2017

热门文章

  1. 十几年Java“老油条”,教你如何才能把Java学好学透彻。
  2. 案例分享:Excel表格的自动化处理和推送
  3. mikrotik监视接口流量
  4. MySql不保存空缺名次排名
  5. PostgreSql中使用ctid去重
  6. English语法_7大句子成分
  7. 鬼门关,黄泉路,彼岸花,忘川河,奈何桥,孟婆汤,三生石(转)
  8. 《Rework》感想和摘录
  9. 华为的离开,那么谁能真正取代?成为国内手机市场的老大?
  10. 小米用上鸿蒙系统,红米小米手机刷新了鸿蒙系统后还能用吗 红米小米手机刷鸿蒙系统图文攻略...