github:地址
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Site :
# @File : 摄像头实时识别.py
import face_recognition
import cv2
#获取网络摄像机#0的参考(默认值)
video_capture = cv2.VideoCapture(0)
# 本地图像
qiqi_image = face_recognition.load_image_file("/Users/xxx/Downloads/test2.png")
qiqi_face_encoding = face_recognition.face_encodings(qiqi_image,num_jitters=3)[0]
zhiyuan_image = face_recognition.load_image_file("/Users/xxx/Downloads/test1.png")
zhiyuan_face_encoding = face_recognition.face_encodings(zhiyuan_image,num_jitters=3)[0]
juwei_image = face_recognition.load_image_file("/Users/xxx/Downloads/test3.jpg")
juwei_face_encoding = face_recognition.face_encodings(juwei_image,num_jitters=3)[0]
known_face_encodings = [
zhiyuan_face_encoding,
juwei_face_encoding,
qiqi_face_encoding
]
known_face_names = [
"zhiyuan",
"juwei",
"yongqi"
]
#初始化一些变量
face_locations = []
face_encodings = []
face_names = []
process_this_frame = True
while True:
# 抓取一帧视频
ret, frame = video_capture.read()
# 将视频帧调整为1/4大小,以加快脸部识别处理
small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
# 将图像从BGR颜色(OpenCV使用的)转换为RGB颜色(face_recognition使用)
rgb_small_frame = small_frame[:, :, ::-1]
# 只处理每隔一帧视频节省时间
if process_this_frame:
# 查找当前视频帧中的所有面部和脸部编码
face_locations = face_recognition.face_locations(rgb_small_frame)
face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations,num_jitters=1)
face_names = []
for face_encoding in face_encodings:
# 查看脸部是否与已知脸部相匹配(S)
matches = face_recognition.compare_faces(known_face_encodings, face_encoding, tolerance=0.35)
name = "Unknown"
# 如果在known_face_encodings中找到了匹配项,只需使用第一个。
# print(len(matches))
if True in matches:
# print(len(matches))
first_match_index = matches.index(True)
# print(first_match_index)
name = known_face_names[first_match_index]
face_names.append(name)
process_this_frame = not process_this_frame
# 显示结果
for (top, right, bottom, left), name in zip(face_locations, face_names):
# 自从我们检测到的框架缩放到1/4尺寸后,缩放后面的位置
top *= 4
right *= 4
bottom *= 4
left *= 4
# 在脸上画一个盒子
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('Video', frame)
# 点击键盘上的'q'退出!
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 释放网络摄像机的资源
video_capture.release()
cv2.destroyAllWindows()