人脸识别代码python完整
时间: 2024-12-21 07:11:23 浏览: 9
人脸识别是一个复杂的过程,涉及到计算机视觉、深度学习和人工智能等多个领域。在Python中,我们可以使用OpenCV库和Dlib库(用于面部关键点检测)或Face_recognition库来实现基本的人脸识别功能。以下是一个简化的例子,使用Face_recognition库进行人脸检测和识别:
```python
# 首先,确保安装了必要的库
!pip install face_recognition numpy
import face_recognition
import cv2
from PIL import Image
# 加载已经识别人脸的数据集(如图片库)
known_faces = []
known_names = []
# 添加已知人脸数据
for i, name in enumerate(['Alice', 'Bob', 'Charlie']): # 假设我们有三个人的脸
for filename in os.listdir(f"faces/{name}"):
image_path = f"faces/{name}/{filename}"
img = face_recognition.load_image_file(image_path)
encoding = face_recognition.face_encodings(img)[0]
known_faces.append(encoding)
known_names.append(name)
# 读取要识别的图像
image_to_identify = face_recognition.load_image_file("test.jpg")
# 对图像进行预处理
rgb_image = image_to_identify[:, :, ::-1]
# 找到图像中的所有脸
face_locations = face_recognition.face_locations(rgb_image)
# 对每个找到的脸进行识别
face_encodings = face_recognition.face_encodings(rgb_image, face_locations)
# 检查每个脸是否匹配已知的人脸
for face_encoding, face_location in zip(face_encodings, face_locations):
matches = face_recognition.compare_faces(known_faces, face_encoding)
name = "Unknown"
if True in matches:
match_index = matches.index(True)
name = known_names[match_index]
# 显示结果
for (top, right, bottom, left), name in zip(face_locations, known_names + [name]):
top *= 2 # Convert back to original scale
right *= 2
bottom *= 2
left *= 2
cv2.rectangle(image_to_identify, (left, top), (right, bottom), (0, 0, 255), 2)
y = top - 15 if top - 15 > 15 else top + 15
cv2.putText(image_to_identify, name, (left, y), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
cv2.imshow('Face Recognition', image_to_identify)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
这个示例假设你有一个名为`faces`的文件夹,里面分别包含每个人的子文件夹,每个子文件夹里有对应人的脸部照片。你需要替换`faces`目录里的实际图片路径,并根据实际需求调整人脸识别的阈值。
阅读全文