人脸识别python代码
时间: 2023-12-08 15:37:58 浏览: 40
以下是一个简单的人脸识别Python代码示例,使用OpenCV和face_recognition库:
```python
import cv2
import face_recognition
# 加载已知人脸图像并编码
known_image = face_recognition.load_image_file("known_person.jpg")
known_face_encoding = face_recognition.face_encodings(known_image)[0]
# 初始化一些变量
face_locations = []
face_encodings = []
face_names = []
process_this_frame = True
# 打开摄像头
video_capture = cv2.VideoCapture(0)
while True:
# 读取摄像头中的一帧
ret, frame = video_capture.read()
# 缩小帧以加快处理速度
small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
# 将BGR颜色转换为RGB颜色
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)
face_names = []
for face_encoding in face_encodings:
# 查看该人脸是否与已知人脸匹配
matches = face_recognition.compare_faces([known_face_encoding], face_encoding)
name = "Unknown"
# 如果找到匹配项,则使用第一个匹配项的名称
if True in matches:
first_match_index = matches.index(True)
name = "Known Person"
face_names.append(name)
process_this_frame = not process_this_frame
# 在人脸周围绘制一个框和名称
for (top, right, bottom, left), name in zip(face_locations, face_names):
# 将帧缩小四倍以进行绘制
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()
```