chemistrymath commited on
Commit
c4e713e
·
verified ·
1 Parent(s): dd8c621

Upload 3 files

Browse files
Files changed (3) hide show
  1. Dockerfile +17 -0
  2. app.py +376 -0
  3. requirements.txt +0 -0
Dockerfile ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Use an official lightweight Python image
2
+ FROM python:3.10
3
+
4
+ # Set the working directory
5
+ WORKDIR /app
6
+
7
+ # Copy all files from the local directory to the container
8
+ COPY . .
9
+
10
+ # Install dependencies
11
+ RUN pip install --no-cache-dir -r requirements.txt
12
+
13
+ # Expose the port Flask will run on
14
+ EXPOSE 7860
15
+
16
+ # Command to run the application using Gunicorn
17
+ CMD ["gunicorn", "--bind", "0.0.0.0:7860", "app:app"]
app.py ADDED
@@ -0,0 +1,376 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+ import cv2
4
+ import numpy as np
5
+ import mediapipe as mp
6
+ import torch
7
+ from flask import Flask, request, jsonify
8
+ from flask_cors import CORS
9
+ import torch.nn.functional as F
10
+
11
+
12
+ app = Flask(__name__)
13
+ CORS(app)
14
+
15
+ mp_pose = mp.solutions.pose
16
+ mp_holistic = mp.solutions.holistic
17
+ pose = mp_pose.Pose(model_complexity=2) # Improved accuracy
18
+ holistic = mp_holistic.Holistic() # For refining pose
19
+
20
+ KNOWN_OBJECT_WIDTH_CM = 21.0 # A4 paper width in cm
21
+ FOCAL_LENGTH = 600 # Default focal length
22
+ DEFAULT_HEIGHT_CM = 152.0 # Default height if not provided
23
+
24
+ # Load depth estimation model
25
+ def load_depth_model():
26
+ model = torch.hub.load("intel-isl/MiDaS", "MiDaS_small")
27
+ model.eval()
28
+ return model
29
+
30
+ depth_model = load_depth_model()
31
+
32
+ def calibrate_focal_length(image, real_width_cm, detected_width_px):
33
+ """Dynamically calibrates focal length using a known object."""
34
+ return (detected_width_px * FOCAL_LENGTH) / real_width_cm if detected_width_px else FOCAL_LENGTH
35
+
36
+
37
+
38
+ def detect_reference_object(image):
39
+ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
40
+ edges = cv2.Canny(gray, 50, 150)
41
+ contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
42
+ if contours:
43
+ largest_contour = max(contours, key=cv2.contourArea)
44
+ x, y, w, h = cv2.boundingRect(largest_contour)
45
+ focal_length = calibrate_focal_length(image, KNOWN_OBJECT_WIDTH_CM, w)
46
+ scale_factor = KNOWN_OBJECT_WIDTH_CM / w
47
+ return scale_factor, focal_length
48
+ return 0.05, FOCAL_LENGTH
49
+
50
+ def estimate_depth(image):
51
+ """Uses AI-based depth estimation to improve circumference calculations."""
52
+ input_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) / 255.0
53
+ input_tensor = torch.tensor(input_image, dtype=torch.float32).permute(2, 0, 1).unsqueeze(0)
54
+
55
+ # Resize input to match MiDaS model input size
56
+ input_tensor = F.interpolate(input_tensor, size=(384, 384), mode="bilinear", align_corners=False)
57
+
58
+ with torch.no_grad():
59
+ depth_map = depth_model(input_tensor)
60
+
61
+ return depth_map.squeeze().numpy()
62
+
63
+ def calculate_distance_using_height(landmarks, image_height, user_height_cm):
64
+ """Calculate distance using the user's known height."""
65
+ top_head = landmarks[mp_pose.PoseLandmark.NOSE.value].y * image_height
66
+ bottom_foot = max(
67
+ landmarks[mp_pose.PoseLandmark.LEFT_ANKLE.value].y,
68
+ landmarks[mp_pose.PoseLandmark.RIGHT_ANKLE.value].y
69
+ ) * image_height
70
+
71
+ person_height_px = abs(bottom_foot - top_head)
72
+
73
+ # Using the formula: distance = (actual_height_cm * focal_length) / height_in_pixels
74
+ distance = (user_height_cm * FOCAL_LENGTH) / person_height_px
75
+
76
+ # Calculate more accurate scale_factor based on known height
77
+ scale_factor = user_height_cm / person_height_px
78
+
79
+ return distance, scale_factor
80
+
81
+ def get_body_width_at_height(frame, height_px, center_x):
82
+ """Scan horizontally at a specific height to find body edges."""
83
+ # Convert to grayscale and apply threshold
84
+ gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
85
+ blur = cv2.GaussianBlur(gray, (5, 5), 0)
86
+ _, thresh = cv2.threshold(blur, 50, 255, cv2.THRESH_BINARY)
87
+
88
+ # Ensure height_px is within image bounds
89
+ if height_px >= frame.shape[0]:
90
+ height_px = frame.shape[0] - 1
91
+
92
+ # Get horizontal line at the specified height
93
+ horizontal_line = thresh[height_px, :]
94
+
95
+ # Find left and right edges starting from center
96
+ center_x = int(center_x * frame.shape[1])
97
+ left_edge, right_edge = center_x, center_x
98
+
99
+ # Scan from center to left
100
+ for i in range(center_x, 0, -1):
101
+ if horizontal_line[i] == 0: # Found edge (black pixel)
102
+ left_edge = i
103
+ break
104
+
105
+ # Scan from center to right
106
+ for i in range(center_x, len(horizontal_line)):
107
+ if horizontal_line[i] == 0: # Found edge (black pixel)
108
+ right_edge = i
109
+ break
110
+
111
+ width_px = right_edge - left_edge
112
+
113
+ # If width is unreasonably small, apply a minimum width
114
+ min_width = 0.1 * frame.shape[1] # Minimum width as 10% of image width
115
+ if width_px < min_width:
116
+ width_px = min_width
117
+
118
+ return width_px
119
+
120
+ def calculate_measurements(results, scale_factor, image_width, image_height, depth_map, frame=None, user_height_cm=None):
121
+ landmarks = results.pose_landmarks.landmark
122
+
123
+ # If user's height is provided, use it to get a more accurate scale factor
124
+ if user_height_cm:
125
+ _, scale_factor = calculate_distance_using_height(landmarks, image_height, user_height_cm)
126
+
127
+ def pixel_to_cm(value):
128
+ return round(value * scale_factor, 2)
129
+
130
+ def calculate_circumference(width_px, depth_ratio=1.0):
131
+ """Estimate circumference using width and depth adjustment."""
132
+ # Using a simplified elliptical approximation: C ≈ 2π * sqrt((a² + b²)/2)
133
+ # where a is half the width and b is estimated depth
134
+ width_cm = width_px * scale_factor
135
+ estimated_depth_cm = width_cm * depth_ratio * 0.7 # Depth is typically ~70% of width for torso
136
+ half_width = width_cm / 2
137
+ half_depth = estimated_depth_cm / 2
138
+ return round(2 * np.pi * np.sqrt((half_width**2 + half_depth**2) / 2), 2)
139
+
140
+ measurements = {}
141
+
142
+ # Shoulder Width
143
+ left_shoulder = landmarks[mp_pose.PoseLandmark.LEFT_SHOULDER.value]
144
+ right_shoulder = landmarks[mp_pose.PoseLandmark.RIGHT_SHOULDER.value]
145
+ shoulder_width_px = abs(left_shoulder.x * image_width - right_shoulder.x * image_width)
146
+
147
+ # Apply a slight correction factor for shoulders (they're usually detected well)
148
+ shoulder_correction = 1.1 # 10% wider
149
+ shoulder_width_px *= shoulder_correction
150
+
151
+ measurements["shoulder_width"] = pixel_to_cm(shoulder_width_px)
152
+
153
+ # Chest/Bust Measurement
154
+ chest_y_ratio = 0.15 # Approximately 15% down from shoulder to hip
155
+ chest_y = left_shoulder.y + (landmarks[mp_pose.PoseLandmark.LEFT_HIP.value].y - left_shoulder.y) * chest_y_ratio
156
+
157
+ chest_correction = 1.15 # 15% wider than detected width
158
+ chest_width_px = abs((right_shoulder.x - left_shoulder.x) * image_width) * chest_correction
159
+
160
+ if frame is not None:
161
+ chest_y_px = int(chest_y * image_height)
162
+ center_x = (left_shoulder.x + right_shoulder.x) / 2
163
+ detected_width = get_body_width_at_height(frame, chest_y_px, center_x)
164
+ if detected_width > 0:
165
+ chest_width_px = max(chest_width_px, detected_width)
166
+
167
+ chest_depth_ratio = 1.0
168
+ if depth_map is not None:
169
+ chest_x = int(((left_shoulder.x + right_shoulder.x) / 2) * image_width)
170
+ chest_y_px = int(chest_y * image_height)
171
+ scale_y = 384 / image_height
172
+ scale_x = 384 / image_width
173
+ chest_y_scaled = int(chest_y_px * scale_y)
174
+ chest_x_scaled = int(chest_x * scale_x)
175
+ if 0 <= chest_y_scaled < 384 and 0 <= chest_x_scaled < 384:
176
+ chest_depth = depth_map[chest_y_scaled, chest_x_scaled]
177
+ max_depth = np.max(depth_map)
178
+ chest_depth_ratio = 1.0 + 0.5 * (1.0 - chest_depth / max_depth)
179
+
180
+ measurements["chest_width"] = pixel_to_cm(chest_width_px)
181
+ measurements["chest_circumference"] = calculate_circumference(chest_width_px, chest_depth_ratio)
182
+
183
+
184
+ # Waist Measurement
185
+ left_hip = landmarks[mp_pose.PoseLandmark.LEFT_HIP.value]
186
+ right_hip = landmarks[mp_pose.PoseLandmark.RIGHT_HIP.value]
187
+
188
+ # Adjust waist_y_ratio to better reflect the natural waistline
189
+ waist_y_ratio = 0.35 # 35% down from shoulder to hip (higher than before)
190
+ waist_y = left_shoulder.y + (left_hip.y - left_shoulder.y) * waist_y_ratio
191
+
192
+ # Use contour detection to dynamically estimate waist width
193
+ if frame is not None:
194
+ waist_y_px = int(waist_y * image_height)
195
+ center_x = (left_hip.x + right_hip.x) / 2
196
+ detected_width = get_body_width_at_height(frame, waist_y_px, center_x)
197
+ if detected_width > 0:
198
+ waist_width_px = detected_width
199
+ else:
200
+ # Fallback to hip width if contour detection fails
201
+ waist_width_px = abs(right_hip.x - left_hip.x) * image_width * 0.9 # 90% of hip width
202
+ else:
203
+ # Fallback to hip width if no frame is provided
204
+ waist_width_px = abs(right_hip.x - left_hip.x) * image_width * 0.9 # 90% of hip width
205
+
206
+ # Apply 30% correction factor to waist width
207
+ waist_correction = 1.16 # 30% wider
208
+ waist_width_px *= waist_correction
209
+
210
+ # Get depth adjustment for waist if available
211
+ waist_depth_ratio = 1.0
212
+ if depth_map is not None:
213
+ waist_x = int(((left_hip.x + right_hip.x) / 2) * image_width)
214
+ waist_y_px = int(waist_y * image_height)
215
+ scale_y = 384 / image_height
216
+ scale_x = 384 / image_width
217
+ waist_y_scaled = int(waist_y_px * scale_y)
218
+ waist_x_scaled = int(waist_x * scale_x)
219
+ if 0 <= waist_y_scaled < 384 and 0 <= waist_x_scaled < 384:
220
+ waist_depth = depth_map[waist_y_scaled, waist_x_scaled]
221
+ max_depth = np.max(depth_map)
222
+ waist_depth_ratio = 1.0 + 0.5 * (1.0 - waist_depth / max_depth)
223
+
224
+ measurements["waist_width"] = pixel_to_cm(waist_width_px)
225
+ measurements["waist"] = calculate_circumference(waist_width_px, waist_depth_ratio)
226
+ # Hip Measurement
227
+ hip_correction = 1.35 # Hips are typically 35% wider than detected landmarks
228
+ hip_width_px = abs(left_hip.x * image_width - right_hip.x * image_width) * hip_correction
229
+
230
+ if frame is not None:
231
+ hip_y_offset = 0.1 # 10% down from hip landmarks
232
+ hip_y = left_hip.y + (landmarks[mp_pose.PoseLandmark.LEFT_KNEE.value].y - left_hip.y) * hip_y_offset
233
+ hip_y_px = int(hip_y * image_height)
234
+ center_x = (left_hip.x + right_hip.x) / 2
235
+ detected_width = get_body_width_at_height(frame, hip_y_px, center_x)
236
+ if detected_width > 0:
237
+ hip_width_px = max(hip_width_px, detected_width)
238
+
239
+ hip_depth_ratio = 1.0
240
+ if depth_map is not None:
241
+ hip_x = int(((left_hip.x + right_hip.x) / 2) * image_width)
242
+ hip_y_px = int(left_hip.y * image_height)
243
+ hip_y_scaled = int(hip_y_px * scale_y)
244
+ hip_x_scaled = int(hip_x * scale_x)
245
+ if 0 <= hip_y_scaled < 384 and 0 <= hip_x_scaled < 384:
246
+ hip_depth = depth_map[hip_y_scaled, hip_x_scaled]
247
+ max_depth = np.max(depth_map)
248
+ hip_depth_ratio = 1.0 + 0.5 * (1.0 - hip_depth / max_depth)
249
+
250
+ measurements["hip_width"] = pixel_to_cm(hip_width_px)
251
+ measurements["hip"] = calculate_circumference(hip_width_px, hip_depth_ratio)
252
+
253
+ # Other measurements (unchanged)
254
+ neck = landmarks[mp_pose.PoseLandmark.NOSE.value]
255
+ left_ear = landmarks[mp_pose.PoseLandmark.LEFT_EAR.value]
256
+ neck_width_px = abs(neck.x * image_width - left_ear.x * image_width) * 2.0
257
+ measurements["neck"] = calculate_circumference(neck_width_px, 1.0)
258
+ measurements["neck_width"] = pixel_to_cm(neck_width_px)
259
+
260
+ left_wrist = landmarks[mp_pose.PoseLandmark.LEFT_WRIST.value]
261
+ sleeve_length_px = abs(left_shoulder.y * image_height - left_wrist.y * image_height)
262
+ measurements["arm_length"] = pixel_to_cm(sleeve_length_px)
263
+
264
+ shirt_length_px = abs(left_shoulder.y * image_height - left_hip.y * image_height) * 1.2
265
+ measurements["shirt_length"] = pixel_to_cm(shirt_length_px)
266
+
267
+ # Thigh Circumference (improved with depth information)
268
+ thigh_y_ratio = 0.2 # 20% down from hip to knee
269
+ left_knee = landmarks[mp_pose.PoseLandmark.LEFT_KNEE.value]
270
+ thigh_y = left_hip.y + (left_knee.y - left_hip.y) * thigh_y_ratio
271
+
272
+ # Apply correction factor for thigh width
273
+ thigh_correction = 1.2 # Thighs are typically wider than what can be estimated from front view
274
+ thigh_width_px = hip_width_px * 0.5 * thigh_correction # Base thigh width on hip width
275
+
276
+ # Use contour detection if frame is available
277
+ if frame is not None:
278
+ thigh_y_px = int(thigh_y * image_height)
279
+ thigh_x = left_hip.x * 0.9 # Move slightly inward from hip
280
+ detected_width = get_body_width_at_height(frame, thigh_y_px, thigh_x)
281
+ if detected_width > 0 and detected_width < hip_width_px: # Sanity check
282
+ thigh_width_px = detected_width # Use detected width
283
+
284
+ # If depth map is available, use it for thigh measurement
285
+ thigh_depth_ratio = 1.0
286
+ if depth_map is not None:
287
+ thigh_x = int(left_hip.x * image_width)
288
+ thigh_y_px = int(thigh_y * image_height)
289
+
290
+ # Scale coordinates to match depth map size
291
+ thigh_y_scaled = int(thigh_y_px * scale_y)
292
+ thigh_x_scaled = int(thigh_x * scale_x)
293
+
294
+ if 0 <= thigh_y_scaled < 384 and 0 <= thigh_x_scaled < 384:
295
+ thigh_depth = depth_map[thigh_y_scaled, thigh_x_scaled]
296
+ max_depth = np.max(depth_map)
297
+ thigh_depth_ratio = 1.0 + 0.5 * (1.0 - thigh_depth / max_depth)
298
+
299
+ measurements["thigh"] = pixel_to_cm(thigh_width_px)
300
+ measurements["thigh_circumference"] = calculate_circumference(thigh_width_px, thigh_depth_ratio)
301
+
302
+
303
+ left_ankle = landmarks[mp_pose.PoseLandmark.LEFT_ANKLE.value]
304
+ trouser_length_px = abs(left_hip.y * image_height - left_ankle.y * image_height)
305
+ measurements["trouser_length"] = pixel_to_cm(trouser_length_px)
306
+
307
+ return measurements
308
+
309
+ @app.route("/upload_images", methods=["POST"])
310
+ def upload_images():
311
+ if "front" not in request.files:
312
+ return jsonify({"error": "Missing front image for reference."}), 400
313
+
314
+ # Get user height if provided, otherwise use default
315
+ user_height_cm = request.form.get('height_cm')
316
+ print(user_height_cm)
317
+ if user_height_cm:
318
+ try:
319
+ user_height_cm = float(user_height_cm)
320
+ except ValueError:
321
+ user_height_cm = DEFAULT_HEIGHT_CM
322
+ else:
323
+ user_height_cm = DEFAULT_HEIGHT_CM
324
+
325
+ received_images = {pose_name: request.files[pose_name] for pose_name in ["front", "left_side", "right_side", "back"] if pose_name in request.files}
326
+ measurements, scale_factor, focal_length, results = {}, None, FOCAL_LENGTH, {}
327
+ frames = {}
328
+
329
+ for pose_name, image_file in received_images.items():
330
+ image_np = np.frombuffer(image_file.read(), np.uint8)
331
+ frame = cv2.imdecode(image_np, cv2.IMREAD_COLOR)
332
+ frames[pose_name] = frame # Store the frame for contour detection
333
+ rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
334
+ results[pose_name] = holistic.process(rgb_frame)
335
+ image_height, image_width, _ = frame.shape
336
+
337
+ if pose_name == "front":
338
+ # Always use height for calibration (default or provided)
339
+ if results[pose_name].pose_landmarks:
340
+ _, scale_factor = calculate_distance_using_height(
341
+ results[pose_name].pose_landmarks.landmark,
342
+ image_height,
343
+ user_height_cm
344
+ )
345
+ else:
346
+ # Fallback to object detection only if pose landmarks aren't detected
347
+ scale_factor, focal_length = detect_reference_object(frame)
348
+
349
+ depth_map = estimate_depth(frame) if pose_name in ["front", "left_side"] else None
350
+
351
+ if results[pose_name].pose_landmarks:
352
+ if pose_name == "front":
353
+ measurements.update(calculate_measurements(
354
+ results[pose_name],
355
+ scale_factor,
356
+ image_width,
357
+ image_height,
358
+ depth_map,
359
+ frames[pose_name], # Pass the frame for contour detection
360
+ user_height_cm
361
+ ))
362
+
363
+ # Debug information to help troubleshoot measurements
364
+ debug_info = {
365
+ "scale_factor": float(scale_factor) if scale_factor else None,
366
+ "focal_length": float(focal_length),
367
+ "user_height_cm": float(user_height_cm)
368
+ }
369
+
370
+ return jsonify({
371
+ "measurements": measurements,
372
+ "debug_info": debug_info
373
+ })
374
+
375
+ if __name__ == '__main__':
376
+ app.run(host='0.0.0.0', port=8001)
requirements.txt ADDED
Binary file (2 kB). View file