基于tensorflow的人脸识别代码
时间: 2023-10-30 19:08:47 浏览: 39
以下是一个基于TensorFlow的人脸识别代码示例:
```python
import tensorflow as tf
import numpy as np
import cv2
import os
# 定义人脸检测器
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# 加载模型
model = tf.keras.models.load_model('model.h5')
# 定义类别标签
class_names = ['Person1', 'Person2', 'Person3']
# 读取测试图像
test_image = cv2.imread('test.jpg')
gray_image = cv2.cvtColor(test_image, cv2.COLOR_BGR2GRAY)
# 检测人脸
faces = face_cascade.detectMultiScale(gray_image, 1.3, 5)
# 遍历每个检测到的人脸
for (x, y, w, h) in faces:
# 在人脸上绘制矩形框
cv2.rectangle(test_image, (x, y), (x+w, y+h), (0, 255, 0), 2)
# 裁剪出人脸区域
face_image = gray_image[y:y+h, x:x+w]
# 调整图像大小为模型输入大小
face_image = cv2.resize(face_image, (224, 224))
# 将图像转换为3通道
face_image = cv2.cvtColor(face_image, cv2.COLOR_GRAY2BGR)
# 将图像转换为模型输入格式
input_image = np.expand_dims(face_image, axis=0)
# 预测人脸的类别
predictions = model.predict(input_image)
# 获取最高概率的类别
predicted_class = np.argmax(predictions[0])
# 获取类别标签
class_label = class_names[predicted_class]
# 在人脸上绘制类别标签
cv2.putText(test_image, class_label, (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
# 显示结果图像
cv2.imshow('Face Recognition', test_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
在这个示例中,我们首先使用OpenCV的人脸检测器检测输入图像中的人脸,然后将每个人脸裁剪出来,并调整大小为模型输入的大小。然后,我们用加载的模型对每个人脸进行分类,并在人脸上绘制预测的类别标签。最后,我们显示结果图像。