facenet人脸识别代码
时间: 2023-11-27 12:05:53 浏览: 72
Facenet是一种基于深度学习的人脸识别算法,其代码实现可以使用TensorFlow框架。以下是一个简单的Facenet人脸识别代码示例:
```python
import tensorflow as tf
import numpy as np
import cv2
import os
# 加载模型
model_path = 'models/20180402-114759.pb'
model = tf.Graph()
with model.as_default():
graph_def = tf.GraphDef()
with tf.gfile.GFile(model_path, 'rb') as f:
serialized_graph = f.read()
graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(graph_def, name='')
# 获取输入和输出张量
input_name = 'input:0'
embeddings_name = 'embeddings:0'
phase_train_name = 'phase_train:0'
with model.as_default():
input_tensor = model.get_tensor_by_name(input_name)
embeddings_tensor = model.get_tensor_by_name(embeddings_name)
phase_train_tensor = model.get_tensor_by_name(phase_train_name)
# 加载人脸检测器
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# 加载人脸图像
img_path = 'test.jpg'
img = cv2.imread(img_path)
# 检测人脸
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
# 提取人脸特征
with tf.Session(graph=model) as sess:
sess.run(tf.global_variables_initializer())
for (x, y, w, h) in faces:
face_img = img[y:y+h, x:x+w]
face_img = cv2.resize(face_img, (160, 160))
face_img = cv2.cvtColor(face_img, cv2.COLOR_BGR2RGB)
face_img = np.expand_dims(face_img, axis=0)
feed_dict = {input_tensor: face_img, phase_train_tensor: False}
embeddings = sess.run(embeddings_tensor, feed_dict=feed_dict)
print(embeddings)
# 相关问题:
阅读全文