0%

python—人脸识别

  • 创建一个images文件夹在同一目录下存放照片作为数据库
  • 代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import face_recognition #导入各个模块
import time
import cv2
import os

def face(path):
known_names=[] #存储知道人名列表
known_encodings=[]#存储知道的特征值
for image_name in os.listdir(path):
load_image = face_recognition.load_image_file(path+image_name) #加载图片
image_face_encoding = face_recognition.face_encodings(load_image)[0] #获得128维特征值
known_names.append(image_name.split(".")[0])
known_encodings.append(image_face_encoding)
#print(load_image)
face_names = [] #存储出现在画面中人脸的名字
video_capture = cv2.VideoCapture(0) #打开摄像头,0表示内置摄像头
process_this_frame = True
while True:
ret, frame = video_capture.read()# 读取摄像头画面
# opencv的图像是BGR格式的,而我们需要是的RGB格式的,因此需要进行一个转换。
rgb_frame = frame[:, :, ::-1]
if process_this_frame:
face_locations = face_recognition.face_locations(rgb_frame)#获得所有人脸位置
face_encodings = face_recognition.face_encodings(rgb_frame, face_locations) #获得人脸特征值
for face_encoding in face_encodings:
matches = face_recognition.compare_faces(known_encodings, face_encoding,tolerance=0.5)
if True in matches:
first_match_index = matches.index(True)
name = known_names[first_match_index]
else:
name="unknown"
face_names.append(name)

process_this_frame = not process_this_frame

# 将捕捉到的人脸显示出来
for (top, right, bottom, left), name in zip(face_locations, face_names):
cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2) # 画人脸矩形框
# 加上人名标签
cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
font = cv2.FONT_HERSHEY_DUPLEX #字体格式
cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)

cv2.imshow('frame', frame)#展示图像

if cv2.waitKey(1) & 0xFF == ord('q'):# 按Q退出
break
video_capture.release()
cv2.destroyAllWindows()
print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
face_name=[]

face_name=set(face_names)
for i in face_name:
print(i+" go into the classroom")


if __name__=='__main__':
face("./images/") #存放已知图像路径

参考:https://blog.csdn.net/weixin_42365428/article/details/88735329