[机器学习][face recognition] 一个视频人脸识别实现

开发环境和用到的库:

  • Ubuntu
  • jupyter notebook(python3.6)
  • OpenCV 
  • Dlib 
  • face_recognition 

实现效果如下(视频截图):

 

 

 

 1 #coding=utf-8
 2 #人脸识别类 - 使用face_recognition模块
 3 import cv2
 4 import face_recognition
 5 import os
 6 
 7 path = "img/face_recognition"  # 模型数据图片目录
 8 cap = cv2.VideoCapture(0)
 9 total_image_name = []
10 total_face_encoding = []
11 for fn in os.listdir(path):  #fn 表示的是文件名q
12     print(path + "/" + fn)
13     total_face_encoding.append(
14         face_recognition.face_encodings(
15             face_recognition.load_image_file(path + "/" + fn))[0])
16     fn = fn[:(len(fn) - 4)]  #截取图片名(这里应该把images文件中的图片名命名为为人物名)
17     total_image_name.append(fn)  #图片名字列表
18 while (1):
19     ret, frame = cap.read()
20     # 发现在视频帧所有的脸和face_enqcodings
21     face_locations = face_recognition.face_locations(frame)
22     face_encodings = face_recognition.face_encodings(frame, face_locations)
23     # 在这个视频帧中循环遍历每个人脸
24     for (top, right, bottom, left), face_encoding in zip(
25             face_locations, face_encodings):
26         # 看看面部是否与已知人脸相匹配。
27         for i, v in enumerate(total_face_encoding):
28             match = face_recognition.compare_faces(
29                 [v], face_encoding, tolerance=0.5)
30             name = "Unknown"
31             if match[0]:
32                 name = total_image_name[i]
33                 break
34         # 画出一个框,框住脸
35         cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 255), 2)
36         # 画出一个带名字的标签,放在框下
37         cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 255, 255),
38                       cv2.FILLED)
39         font = cv2.FONT_HERSHEY_DUPLEX
40         cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0,
41                     (255, 255, 255), 1)
42     # 显示结果图像
43     cv2.imshow('Video', frame)
44     if cv2.waitKey(1) & 0xFF == ord('q'):
45         break
46 
47 cap.release()
48 cv2.destroyAllWindows()

 

 

 

posted on 2018-05-09 07:25  fox17  阅读(1963)  评论(0编辑  收藏  举报

导航