frame2face-1.bak 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. from flask import Flask, request, jsonify
  2. import cv2
  3. import dlib
  4. import numpy as np
  5. from scipy.spatial import distance
  6. app = Flask(__name__)
  7. # 加载 Dlib 的人脸检测器和关键点检测器
  8. detector = dlib.get_frontal_face_detector()
  9. predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
  10. def get_face_landmarks(image):
  11. """
  12. 获取图像中的人脸轮廓关键点
  13. """
  14. gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  15. faces = detector(gray)
  16. if len(faces) == 0:
  17. return None
  18. # 只处理第一张人脸
  19. face = faces[0]
  20. landmarks = predictor(gray, face)
  21. return np.array([[p.x, p.y] for p in landmarks.parts()])
  22. def compare_contours(contour1, contour2):
  23. """
  24. 比较两个轮廓的相似度,返回偏移评估值
  25. """
  26. if contour1 is None or contour2 is None:
  27. return None
  28. # 计算两个轮廓之间的欧氏距离
  29. dist = distance.cdist(contour1, contour2, 'euclidean')
  30. # 返回平均偏移值
  31. return np.mean(dist)
  32. @app.route('/upload', methods=['POST'])
  33. def upload_image():
  34. """
  35. 处理前端上传的照片,计算轮廓偏移值
  36. """
  37. if 'file' not in request.files:
  38. return jsonify({"error": "No file uploaded"}), 400
  39. file = request.files['file']
  40. if file.filename == '':
  41. return jsonify({"error": "No file selected"}), 400
  42. # 读取上传的图像
  43. image = cv2.imdecode(np.frombuffer(file.read(), np.uint8), cv2.IMREAD_COLOR)
  44. if image is None:
  45. return jsonify({"error": "Failed to read image"}), 400
  46. # 获取上传图像的人脸轮廓
  47. uploaded_contour = get_face_landmarks(image)
  48. if uploaded_contour is None:
  49. return jsonify({"error": "No face detected in uploaded image"}), 400
  50. # 读取标准图像
  51. standard_image = cv2.imread("standard_face.jpg")
  52. if standard_image is None:
  53. return jsonify({"error": "Failed to read standard image"}), 400
  54. # 获取标准图像的人脸轮廓
  55. standard_contour = get_face_landmarks(standard_image)
  56. if standard_contour is None:
  57. return jsonify({"error": "No face detected in standard image"}), 400
  58. # 比较两个轮廓
  59. offset_value = compare_contours(uploaded_contour, standard_contour)
  60. if offset_value is None:
  61. return jsonify({"error": "Failed to compare contours"}), 400
  62. # 返回偏移评估值
  63. return jsonify({"offset_value": float(offset_value)}), 200
  64. if __name__ == '__main__':
  65. app.run(host='0.0.0.0', port=5000)