发布于 2026-01-06 3 阅读
0

如何使用 Python 和 FaceNet 构建人脸识别系统

如何使用 Python 和 FaceNet 构建人脸识别系统

人脸识别技术已在从安防系统到社交媒体等各种应用中日益普及。FaceNet 是执行此任务最有效的模型之一,它是一种专为人脸验证、识别和聚类而设计的深度学习模型。

在本教程中,我将向您展示如何使用 FaceNet 在 Python 中构建人脸识别系统。我们将涵盖从加载模型到人脸比对的所有内容。完成本指南后,您将拥有在自己的项目中实现人脸识别的扎实基础。

FaceNet是什么?

FaceNet 是谷歌开发的一种深度学习模型,它将人脸映射到 128 维欧氏空间。这些嵌入向量代表了人脸的基本特征,使得人脸的比较和识别更加容易,准确率也更高。与传统的人脸识别方法不同,FaceNet 专注于嵌入学习,这使其具有高效性和可扩展性。

先决条件

在深入研究代码之前,请确保已安装以下软件:

  • Python 3.x
  • TensorFlow 或 Keras(用于深度学习模型)
  • NumPy(用于数值运算)
  • OpenCV(用于图像处理)
  • Scikit-learn(用于应用最近邻搜索)

您可以使用 pip 安装这些依赖项:

pip install tensorflow numpy opencv-python scikit-learn
Enter fullscreen mode Exit fullscreen mode

步骤 1:加载预训练的 FaceNet 模型

首先,我们将加载一个预训练的 FaceNet 模型。您可以从可信来源下载该模型,也可以使用库中提供的模型keras-facenet

from keras.models import load_model

# Load the pre-trained FaceNet model
model = load_model('facenet_keras.h5')
print("Model Loaded Successfully")
Enter fullscreen mode Exit fullscreen mode

加载模型是设置人脸识别系统的第一步。该模型将用于生成图像的嵌入向量,这些嵌入向量是人脸的数值表示。

步骤 2:FaceNet 图像预处理

FaceNet要求输入图像为160x160像素的RGB格式。此外,像素值在输入模型之前需要进行归一化处理。

import cv2
import numpy as np

def preprocess_image(image_path):
    # Load the image using OpenCV
    img = cv2.imread(image_path)

    # Convert the image to RGB (FaceNet expects RGB images)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

    # Resize the image to 160x160 pixels
    img = cv2.resize(img, (160, 160))

    # Normalize the pixel values
    img = img.astype('float32') / 255.0

    # Expand dimensions to match the input shape of FaceNet (1, 160, 160, 3)
    img = np.expand_dims(img, axis=0)

    return img
Enter fullscreen mode Exit fullscreen mode

此函数负责 FaceNet 所需的图像预处理。它将图像转换为合适的格式和大小,确保模型接收到能够有效处理的输入。

步骤 3:生成人脸嵌入

接下来,我们将使用 FaceNet 模型从预处理后的图像中生成嵌入向量。这些嵌入向量将作为人脸的唯一数值表示。

def get_face_embedding(model, image_path):
    # Preprocess the image
    img = preprocess_image(image_path)

    # Generate the embedding
    embedding = model.predict(img)

    return embedding
Enter fullscreen mode Exit fullscreen mode

get_face_embedding函数接收模型和图像路径作为参数,处理图像,并返回嵌入向量。我们将使用此嵌入向量进行人脸比较。

步骤 4:使用嵌入比较人脸

为了判断两张人脸是否匹配,我们通过计算它们之间的欧氏距离来比较它们的嵌入向量。如果距离低于某个阈值,则认为这两张人脸匹配。

from numpy import linalg as LA

def compare_faces(embedding1, embedding2, threshold=0.5):
    # Compute the Euclidean distance between the embeddings
    distance = LA.norm(embedding1 - embedding2)

    # Compare the distance to the threshold
    if distance < threshold:
        print("Face Matched.")
    else:
        print("Faces are different.")

    return distance
Enter fullscreen mode Exit fullscreen mode

compare_faces函数计算两个嵌入之间的距离。如果该距离小于指定的阈值(默认为 0.5),则函数输出“人脸匹配”。否则,输出“人脸不同”。

第五步:测试人脸识别系统

最后,让我们用两张图片测试一下我们的人脸识别系统,看看它是否能正确识别出它们是同一个人。

# Load the FaceNet model
model = load_model('facenet_keras.h5')

# Get embeddings for two images
embedding1 = get_face_embedding(model, 'face1.jpg')
embedding2 = get_face_embedding(model, 'face2.jpg')

# Compare the two faces
distance = compare_faces(embedding1, embedding2)

print(f"Euclidean Distance: {distance}")
Enter fullscreen mode Exit fullscreen mode

输出

  • 如果面孔匹配,你会看到:Face Matched.
  • 如果它们不匹配,你会看到:Faces are different.

此外,还会打印出两个嵌入之间的欧氏距离。

结论

您刚刚使用 Python 中的 FaceNet 构建了一个简单而强大的面部识别系统。该系统可以轻松扩展,以识别更多面部、处理实时识别或集成到更大的项目中。FaceNet 的高精度和高效率使其成为面部识别任务的绝佳选择。

您可以随意尝试不同的阈值,或者尝试将此系统用于实时应用程序,例如基于网络摄像头的面部识别工具。

如果您有任何疑问或需要进一步帮助,请在下方留言。祝您编程愉快!


文章来源:https://dev.to/abhinowww/how-to-build-a-face-recognition-system-using-facenet-in-python-27kh