代码拉取完成,页面将自动刷新
from flask import Flask, request, jsonify, render_template, url_for
from PIL import Image
import os
import numpy as np
import config
import face_recognition
from utils import faceUtils
app = Flask(__name__)
@app.route('/upload_face', methods=['POST'])
def upload_face_api():
if 'file' not in request.files:
return jsonify({'error': 'No file part in the request'}), 400
# 检查文件大小(例如,限制为 2MB)
file = request.files['file']
if file.content_length > 2 * 1024 * 1024:
return jsonify({'error': 'File is too large'}), 400
name = file.filename.split('.')[0]
try:
# 创建一个唯一的文件名
image_path = os.path.join(config.UPLOAD_FOLDER, file.filename)
encoding_path = os.path.join(config.UPLOAD_FOLDER, f"{name}.npy")
# 将上传的文件保存到磁盘
file.save(image_path)
# 加载图像并转换为 RGB
image = Image.open(image_path).convert('RGB')
image_np = np.array(image)
# 使用 face_recognition 提取人脸特征
face_locations = face_recognition.face_locations(image_np)
if len(face_locations) == 0:
return jsonify({'error': 'No faces found in the image'}), 400
face_encodings = face_recognition.face_encodings(image_np, face_locations)
# 假设只处理图像中的第一张脸 将新上传的人脸特征和姓名存储到字典中
face_encoding = face_encodings[0]
faceUtils.face_data[name] = face_encoding
# 将特征保存为 NumPy 文件
np.save(encoding_path, face_encoding)
return jsonify({'message': 'Face uploaded and features extracted successfully'}), 200
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/compare_faces', methods=['POST'])
def compare_faces_api():
if 'face' not in request.files:
return jsonify({'error': 'No face image part in the request'}), 400
face = request.files['face']
try:
# 加载并处理上传的人脸图像
image1 = Image.open(face).convert('RGB')
image1_np = np.array(image1)
face_locations1 = face_recognition.face_locations(image1_np)
if len(face_locations1) == 0:
return jsonify({'error': 'No faces found in the image'}), 400
face_encodings1 = face_recognition.face_encodings(image1_np, face_locations1)
face_encoding1 = face_encodings1[0]
# 比较上传的人脸与已知人脸
best_match, best_distance = faceUtils.compare_faces(face_encoding1)
if best_match is None:
return jsonify({'matched_name': 'Unknown', 'confidence': best_distance}), 200
else:
return jsonify({'matched_name': best_match, 'confidence': best_distance}), 200
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/list_faces', methods=['GET'])
def list_faces():
images = os.listdir(config.UPLOAD_FOLDER)
image_files = [{'filename': f, 'url': url_for('static', filename='uploads/' + f)}
for f in images if f.lower().endswith(('.png', '.jpg', '.jpeg', '.gif'))]
return jsonify(image_files)
@app.route('/')
def index():
# 渲染 templates 文件夹中的 index.html 文件
return render_template('index.html')
if __name__ == '__main__':
faceUtils.load_known_face_encodings()
app.run(debug=True)
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。