python实现人脸识别系统

要实现一个人脸识别系统,可以使用Python语言和一些常用的开源库。以下是一个基于深度学习的人脸识别系统的代码示例,使用的是FaceNet模型。

首先,需要安装相关的库,包括OpenCV、Keras、Tensorflow等:

pip install opencv-python keras tensorflow

然后,需要准备人脸数据集和模型。假设数据集中包含多个人的人脸图像,每个人的图像存储在一个单独的文件夹中,文件夹的名称即为该人的姓名。

接下来是代码实现:

import cv2
import os
import numpy as np
from keras.models import load_model
from keras.preprocessing import image

# 加载FaceNet模型
model = load_model('facenet_keras.h5')

# 获取人脸嵌入向量
def get_embedding(face):
    # 对人脸图像进行预处理
    face = cv2.resize(face, (160, 160))
    face = face.astype('float32')
    mean, std = face.mean(), face.std()
    face = (face - mean) / std
    face = np.expand_dims(face, axis=0)
    # 通过FaceNet模型获取嵌入向量
    embedding = model.predict(face)[0]
    return embedding

# 加载人脸库
def load_face_dataset(path):
    face_db = {}
    for name in os.listdir(path):
        person_dir = os.path.join(path, name)
        embeddings = []
        for file_name in os.listdir(person_dir):
            file_path = os.path.join(person_dir, file_name)
            img = image.load_img(file_path, target_size=(160, 160))
            face = image.img_to_array(img)
            embedding = get_embedding(face)
            embeddings.append(embedding)
        face_db[name] = embeddings
    return face_db

# 计算欧氏距离
def euclidean_distance(x1, x2):
    return np.sqrt(np.sum(np.square(x1 - x2)))

# 人脸识别
def recognize_face(face, face_db):
    embedding = get_embedding(face)
    min_dist = 100
    name = "unknown"
    for key, embeddings in face_db.items():
        for db_embedding in embeddings:
            dist = euclidean_distance(db_embedding, embedding)
            if dist < min_dist:
                min_dist = dist
                name = key
    return name, min_dist

# 加载人脸库
face_db = load_face_dataset('face_dataset')

# 打开摄像头进行人脸识别
cap = cv2.VideoCapture(0)
while True:
    # 读取视频帧
    ret, frame = cap.read()
    if not ret:
        break
    # 进行人脸检测
    faces = detect_faces(frame)
    # 针对每个检测到的人脸进行识别
    for face in faces:
        name, dist = recognize_face(face, face_db)
        # 绘制识别结果
        x, y, w, h = face
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)

猜你喜欢

转载自blog.csdn.net/qq_39162487/article/details/129857132