maham234 commited on
Commit
c8438bd
·
verified ·
1 Parent(s): d590f23

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -21
app.py CHANGED
@@ -1,24 +1,35 @@
1
  from flask import Flask, request, jsonify
 
2
  import cv2
3
  import mediapipe as mp
4
  import numpy as np
5
  from PIL import Image
6
  import base64
7
  import io
8
- from flask_cors import CORS
9
 
 
10
  app = Flask(__name__)
11
- CORS(app) # Allow cross-origin requests from Flutter app
12
 
13
- # MediaPipe Pose
14
- mp_pose = mp.solutions.pose
15
- pose = mp_pose.Pose(static_image_mode=False, min_detection_confidence=0.5)
16
- mp_drawing = mp.solutions.drawing_utils
17
 
18
- # Overlay function
 
 
 
 
 
 
 
 
 
 
19
  def overlay_dress(frame, dress, landmarks):
 
20
  if landmarks is not None:
21
  h, w, _ = frame.shape
 
22
  def to_pixel(lm):
23
  return int(lm.x * w), int(lm.y * h)
24
 
@@ -27,34 +38,37 @@ def overlay_dress(frame, dress, landmarks):
27
  left_hip = to_pixel(landmarks[mp_pose.PoseLandmark.LEFT_HIP.value])
28
  right_hip = to_pixel(landmarks[mp_pose.PoseLandmark.RIGHT_HIP.value])
29
 
30
- # Dress size & position
31
- dress_width = int(np.linalg.norm(np.array(left_shoulder)-np.array(right_shoulder))*1.8)
32
  top_shoulder_y = min(left_shoulder[1], right_shoulder[1])
33
  bottom_hip_y = max(left_hip[1], right_hip[1])
34
- dress_height = int((bottom_hip_y - top_shoulder_y)*1.2)
35
 
36
- center_x = (left_shoulder[0]+right_shoulder[0])//2
37
- x1 = max(center_x - dress_width//2, 0)
38
  y1 = max(top_shoulder_y - 30, 0)
39
  x2 = min(x1 + dress_width, w)
40
  y2 = min(y1 + dress_height, h)
41
 
42
- # Resize and blend dress
43
- dress_resized = cv2.resize(dress, (x2-x1, y2-y1), interpolation=cv2.INTER_AREA)
44
- if dress_resized.shape[2] == 4: # has alpha channel
45
  alpha_s = dress_resized[:, :, 3] / 255.0
46
  alpha_l = 1.0 - alpha_s
47
  for c in range(3):
48
- frame[y1:y2, x1:x2, c] = alpha_s*dress_resized[:, :, c] + alpha_l*frame[y1:y2, x1:x2, c]
 
 
49
 
50
  return frame
51
 
52
- # Home route for HF Spaces detection
 
53
  @app.route("/", methods=["GET"])
54
  def home():
55
- return "<h1>Flask API is running!</h1>"
 
56
 
57
- # Virtual try-on API
58
  @app.route("/tryon", methods=["POST"])
59
  def tryon():
60
  try:
@@ -80,7 +94,7 @@ def tryon():
80
  # Overlay dress
81
  frame = overlay_dress(frame, dress_img, landmarks)
82
 
83
- # Draw pose landmarks
84
  if results.pose_landmarks:
85
  mp_drawing.draw_landmarks(frame, results.pose_landmarks, mp_pose.POSE_CONNECTIONS)
86
 
@@ -91,7 +105,12 @@ def tryon():
91
  return jsonify({"image": img_base64})
92
 
93
  except Exception as e:
 
 
94
  return jsonify({"error": str(e)}), 500
95
 
 
 
96
  if __name__ == "__main__":
97
- app.run(host="0.0.0.0", port=5000)
 
 
1
  from flask import Flask, request, jsonify
2
+ from flask_cors import CORS
3
  import cv2
4
  import mediapipe as mp
5
  import numpy as np
6
  from PIL import Image
7
  import base64
8
  import io
9
+ import traceback
10
 
11
+ # Initialize Flask
12
  app = Flask(__name__)
13
+ CORS(app) # Allow cross-origin requests (for Flutter or frontend)
14
 
15
+ print("✅ Flask app starting...")
 
 
 
16
 
17
+ try:
18
+ # Initialize MediaPipe Pose
19
+ mp_pose = mp.solutions.pose
20
+ pose = mp_pose.Pose(static_image_mode=False, min_detection_confidence=0.5)
21
+ mp_drawing = mp.solutions.drawing_utils
22
+ print("✅ MediaPipe initialized successfully")
23
+ except Exception as e:
24
+ print("❌ Error initializing MediaPipe:", e)
25
+ traceback.print_exc()
26
+
27
+ # ---------- Helper function ----------
28
  def overlay_dress(frame, dress, landmarks):
29
+ """Overlay a dress image on the user's frame based on pose landmarks."""
30
  if landmarks is not None:
31
  h, w, _ = frame.shape
32
+
33
  def to_pixel(lm):
34
  return int(lm.x * w), int(lm.y * h)
35
 
 
38
  left_hip = to_pixel(landmarks[mp_pose.PoseLandmark.LEFT_HIP.value])
39
  right_hip = to_pixel(landmarks[mp_pose.PoseLandmark.RIGHT_HIP.value])
40
 
41
+ # Estimate size and position of the dress
42
+ dress_width = int(np.linalg.norm(np.array(left_shoulder) - np.array(right_shoulder)) * 1.8)
43
  top_shoulder_y = min(left_shoulder[1], right_shoulder[1])
44
  bottom_hip_y = max(left_hip[1], right_hip[1])
45
+ dress_height = int((bottom_hip_y - top_shoulder_y) * 1.2)
46
 
47
+ center_x = (left_shoulder[0] + right_shoulder[0]) // 2
48
+ x1 = max(center_x - dress_width // 2, 0)
49
  y1 = max(top_shoulder_y - 30, 0)
50
  x2 = min(x1 + dress_width, w)
51
  y2 = min(y1 + dress_height, h)
52
 
53
+ # Resize and overlay
54
+ dress_resized = cv2.resize(dress, (x2 - x1, y2 - y1), interpolation=cv2.INTER_AREA)
55
+ if dress_resized.shape[2] == 4: # if dress has alpha channel
56
  alpha_s = dress_resized[:, :, 3] / 255.0
57
  alpha_l = 1.0 - alpha_s
58
  for c in range(3):
59
+ frame[y1:y2, x1:x2, c] = (
60
+ alpha_s * dress_resized[:, :, c] + alpha_l * frame[y1:y2, x1:x2, c]
61
+ )
62
 
63
  return frame
64
 
65
+
66
+ # ---------- Routes ----------
67
  @app.route("/", methods=["GET"])
68
  def home():
69
+ return "<h1>✅ Flask Virtual Try-On API is Running!</h1>"
70
+
71
 
 
72
  @app.route("/tryon", methods=["POST"])
73
  def tryon():
74
  try:
 
94
  # Overlay dress
95
  frame = overlay_dress(frame, dress_img, landmarks)
96
 
97
+ # Draw pose landmarks (optional for debugging)
98
  if results.pose_landmarks:
99
  mp_drawing.draw_landmarks(frame, results.pose_landmarks, mp_pose.POSE_CONNECTIONS)
100
 
 
105
  return jsonify({"image": img_base64})
106
 
107
  except Exception as e:
108
+ print("❌ Error during /tryon:", e)
109
+ traceback.print_exc()
110
  return jsonify({"error": str(e)}), 500
111
 
112
+
113
+ # ---------- Local Debug Mode ----------
114
  if __name__ == "__main__":
115
+ # Only for local testing (Gunicorn will handle production)
116
+ app.run(debug=True, host="0.0.0.0", port=5000)