欢迎访问宙启技术站
智能推送

使用VGG16模型进行人脸识别的python实现与代码示例

发布时间:2023-12-15 18:20:53

VGG16是一种深度卷积神经网络模型,原先是为了解决图像分类问题而设计的。然而,由于其强大的性能和泛化能力,它也可以用于人脸识别任务。

下面是使用VGG16进行人脸识别的Python实现示例代码:

首先,我们需要导入必要的库:

import cv2
import numpy as np
from keras.applications.vgg16 import VGG16, preprocess_input
from keras.preprocessing import image
from keras.models import Model
from keras.layers import Dense, GlobalAveragePooling2D
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import Normalizer
from sklearn.svm import SVC

接下来,我们定义一些辅助函数:

def load_image(img_path):
    img = cv2.imread(img_path)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    img = cv2.resize(img, (224, 224))
    return img

def extract_face_features(img_path, model):
    img = load_image(img_path)
    x = image.img_to_array(img)
    x = np.expand_dims(x, axis=0)
    x = preprocess_input(x)
    features = model.predict(x)
    return features

def train_classifier(X_train, y_train):
    model = SVC(kernel='linear', probability=True)
    model.fit(X_train, y_train)
    return model

def predict_class(img_path, model, le):
    features = extract_face_features(img_path, base_model)
    y_pred = model.predict(features)
    y_pred_label = le.inverse_transform(y_pred)[0]
    return y_pred_label

接下来,我们加载预训练的VGG16模型,并从最后一个全连接层之前提取特征:

base_model = VGG16(weights='imagenet', include_top=False)
x = base_model.output
x = GlobalAveragePooling2D()(x)
x = Dense(512, activation='relu')(x)
x = Dense(512, activation='relu')(x)
x = Dense(256, activation='relu')(x)
predictions = Dense(num_classes, activation='softmax')(x)

model = Model(inputs=base_model.input, outputs=predictions)

在这个示例中,我们使用全局平均池化层和多个全连接层来定义模型的结构。请注意,上面的代码片段中的「num_classes」是指分类的类别数量。

然后,我们加载包含训练数据的图像并提取它们的特征向量:

img_paths = ['img1.jpg', 'img2.jpg', 'img3.jpg']
X_train = []
y_train = []

for img_path in img_paths:
    features = extract_face_features(img_path, base_model)
    X_train.append(features)
    y_train.append('person1') 

X_train = np.array(X_train)
le = LabelEncoder()
y_train = le.fit_transform(y_train)

以上代码加载图像并提取每个图像的特征,存储在X_train和y_train变量中。在此示例中,我们使用了图像路径的列表和相应的标签,以及LabelEncoder用于将标签编码为数字。

接下来,我们使用提取的特征向量和标签来训练分类器:

model = train_classifier(X_train, y_train)

最后,我们可以使用训练好的分类器对新的图像进行预测:

img_path = 'img4.jpg'
predicted_label = predict_class(img_path, model, le)
print(predicted_label)

在这个示例中,我们提供了一个新的图像路径,然后通过调用predict_class函数来获取预测的标签。

这就是使用VGG16模型进行人脸识别的Python实现示例代码。你可以根据自己的需求进行修改和优化。