Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -124,7 +124,204 @@
|
|
| 124 |
# demo.launch()
|
| 125 |
|
| 126 |
|
| 127 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
import json
|
| 129 |
import base64
|
| 130 |
import requests
|
|
@@ -132,166 +329,146 @@ from io import BytesIO
|
|
| 132 |
import torch
|
| 133 |
import numpy as np
|
| 134 |
import cv2
|
| 135 |
-
import json
|
| 136 |
import os
|
| 137 |
-
|
| 138 |
-
from detectron2.
|
| 139 |
-
from detectron2.
|
| 140 |
from detectron2 import model_zoo
|
| 141 |
-
import torch_utils
|
| 142 |
-
import dnnlib
|
| 143 |
-
# Create output directory if it doesn't exist
|
| 144 |
-
output_dir = "key/"
|
| 145 |
-
os.makedirs(output_dir, exist_ok=True)
|
| 146 |
-
output_file = os.path.join(output_dir, "keypoints.json")
|
| 147 |
-
|
| 148 |
-
|
| 149 |
|
| 150 |
-
#
|
| 151 |
cfg = get_cfg()
|
| 152 |
cfg.merge_from_file(model_zoo.get_config_file("COCO-Keypoints/keypoint_rcnn_R_50_FPN_3x.yaml"))
|
| 153 |
cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url("COCO-Keypoints/keypoint_rcnn_R_50_FPN_3x.yaml")
|
| 154 |
cfg.MODEL.DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 155 |
-
|
| 156 |
-
# Load the predictor
|
| 157 |
predictor = DefaultPredictor(cfg)
|
| 158 |
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
# Run keypoint detection
|
| 164 |
-
outputs = predictor(image)
|
| 165 |
|
| 166 |
-
|
|
|
|
|
|
|
|
|
|
| 167 |
instances = outputs["instances"]
|
| 168 |
keypoints = instances.pred_keypoints.cpu().numpy().tolist() if instances.has("pred_keypoints") else None
|
| 169 |
|
| 170 |
if not keypoints:
|
| 171 |
-
return "No keypoints detected.", None
|
| 172 |
-
|
| 173 |
-
# Save keypoints to JSON
|
| 174 |
-
with open(output_file, "w") as f:
|
| 175 |
-
json.dump({"keypoints": keypoints}, f, indent=4)
|
| 176 |
|
| 177 |
-
keypoints = np.array(keypoints[0])[:, :2]
|
| 178 |
|
| 179 |
-
#
|
| 180 |
-
NOSE, L_SHOULDER, R_SHOULDER = 0, 5, 6
|
| 181 |
-
L_ELBOW, R_ELBOW = 7, 8
|
| 182 |
-
L_WRIST, R_WRIST = 9, 10
|
| 183 |
-
L_HIP, R_HIP = 11, 12
|
| 184 |
-
L_ANKLE, R_ANKLE = 15, 16
|
| 185 |
-
|
| 186 |
-
# Define Keypoint Pairs for Drawing Lines (COCO Format)
|
| 187 |
skeleton = [(5, 6), (5, 11), (6, 12), (11, 12)]
|
| 188 |
-
|
| 189 |
-
# Draw Keypoints
|
| 190 |
for x, y in keypoints:
|
| 191 |
-
cv2.circle(
|
| 192 |
-
|
| 193 |
-
# Draw Skeleton
|
| 194 |
for pt1, pt2 in skeleton:
|
| 195 |
x1, y1 = map(int, keypoints[pt1])
|
| 196 |
x2, y2 = map(int, keypoints[pt2])
|
| 197 |
-
cv2.line(
|
| 198 |
|
| 199 |
-
#
|
| 200 |
-
|
| 201 |
-
|
| 202 |
|
| 203 |
-
# Calculate full height (consider head length)
|
| 204 |
ankle_mid = ((keypoints[L_ANKLE] + keypoints[R_ANKLE]) / 2).tolist()
|
| 205 |
pixel_height = get_distance(keypoints[NOSE], ankle_mid)
|
| 206 |
-
|
| 207 |
-
# Estimated full body height (add approx head length)
|
| 208 |
-
estimated_full_pixel_height = pixel_height / 0.87 # Since 87% = nose to ankle
|
| 209 |
pixels_per_cm = estimated_full_pixel_height / user_height_cm
|
| 210 |
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
waist_width_px = get_distance(keypoints[L_HIP], keypoints[R_HIP])
|
| 214 |
-
|
| 215 |
-
# Convert to cm
|
| 216 |
-
shoulder_width_cm = shoulder_width_px / pixels_per_cm
|
| 217 |
-
waist_width_cm = waist_width_px / pixels_per_cm
|
| 218 |
-
|
| 219 |
-
# Torso Length (Neck to Pelvis)
|
| 220 |
pelvis = ((keypoints[L_HIP] + keypoints[R_HIP]) / 2).tolist()
|
| 221 |
neck = ((keypoints[L_SHOULDER] + keypoints[R_SHOULDER]) / 2).tolist()
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
# Arm Length (Shoulder to Wrist)
|
| 226 |
-
arm_length_px = get_distance(keypoints[L_SHOULDER], keypoints[L_WRIST])
|
| 227 |
-
arm_length_cm = arm_length_px / pixels_per_cm
|
| 228 |
|
| 229 |
-
# Calculate waist and hip circumference (Ellipse approximation)
|
| 230 |
-
# Waist circumference ≈ π × (waist_width / 2) × 2
|
| 231 |
waist_circumference = np.pi * waist_width_cm
|
| 232 |
-
hip_circumference = waist_circumference / 0.75
|
| 233 |
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
"Full Arm Length (Shoulder to Wrist, cm)": round(arm_length_cm, 2),
|
| 242 |
-
}
|
| 243 |
|
| 244 |
-
measurements
|
| 245 |
|
| 246 |
-
|
| 247 |
-
|
|
|
|
|
|
|
| 248 |
|
| 249 |
-
# Save to database function
|
| 250 |
-
def save_to_database(measurements, image, user_height_cm):
|
| 251 |
if measurements is None or image is None:
|
| 252 |
-
return "No data to save."
|
| 253 |
|
| 254 |
-
# Convert image to base64
|
| 255 |
buffered = BytesIO()
|
| 256 |
-
pil_image = Image.fromarray(image)
|
| 257 |
pil_image.save(buffered, format="JPEG")
|
| 258 |
img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
|
| 259 |
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
"
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
"
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 272 |
)
|
| 273 |
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
# Gradio interface setup
|
| 280 |
-
def process_and_save(image, user_height_cm):
|
| 281 |
-
measurements, processed_image = process_image(image, user_height_cm)
|
| 282 |
-
if measurements:
|
| 283 |
-
save_message = save_to_database(measurements, processed_image, user_height_cm)
|
| 284 |
-
return processed_image, measurements, save_message
|
| 285 |
-
else:
|
| 286 |
-
return None, None, "Error in processing image."
|
| 287 |
-
|
| 288 |
-
# Gradio interface setup
|
| 289 |
-
iface = gr.Interface(
|
| 290 |
-
fn=process_and_save,
|
| 291 |
-
inputs=[gr.Image(type="numpy"), gr.Number(label="User Height (cm)")],
|
| 292 |
-
outputs=[gr.Image(type="numpy"), gr.JSON(), gr.Textbox()],
|
| 293 |
-
live=True
|
| 294 |
-
)
|
| 295 |
-
|
| 296 |
-
iface.launch(share=True)
|
| 297 |
|
|
|
|
|
|
|
|
|
| 124 |
# demo.launch()
|
| 125 |
|
| 126 |
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
# from PIL import Image # Importing Image from PIL (Pillow)
|
| 152 |
+
# import json
|
| 153 |
+
# import base64
|
| 154 |
+
# import requests
|
| 155 |
+
# from io import BytesIO
|
| 156 |
+
# import torch
|
| 157 |
+
# import numpy as np
|
| 158 |
+
# import cv2
|
| 159 |
+
# import json
|
| 160 |
+
# import os
|
| 161 |
+
# import gradio as gr
|
| 162 |
+
# from detectron2.detectron2.engine import DefaultPredictor
|
| 163 |
+
# from detectron2.detectron2.config import get_cfg
|
| 164 |
+
# from detectron2 import model_zoo
|
| 165 |
+
# import torch_utils
|
| 166 |
+
# import dnnlib
|
| 167 |
+
# # Create output directory if it doesn't exist
|
| 168 |
+
# output_dir = "key/"
|
| 169 |
+
# os.makedirs(output_dir, exist_ok=True)
|
| 170 |
+
# output_file = os.path.join(output_dir, "keypoints.json")
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
# # Load pre-trained Keypoint R-CNN model
|
| 175 |
+
# cfg = get_cfg()
|
| 176 |
+
# cfg.merge_from_file(model_zoo.get_config_file("COCO-Keypoints/keypoint_rcnn_R_50_FPN_3x.yaml"))
|
| 177 |
+
# cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url("COCO-Keypoints/keypoint_rcnn_R_50_FPN_3x.yaml")
|
| 178 |
+
# cfg.MODEL.DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 179 |
+
|
| 180 |
+
# # Load the predictor
|
| 181 |
+
# predictor = DefaultPredictor(cfg)
|
| 182 |
+
|
| 183 |
+
# def process_image(image, user_height_cm):
|
| 184 |
+
# # Convert Gradio image input to OpenCV format
|
| 185 |
+
# image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
|
| 186 |
+
|
| 187 |
+
# # Run keypoint detection
|
| 188 |
+
# outputs = predictor(image)
|
| 189 |
+
|
| 190 |
+
# # Extract keypoints
|
| 191 |
+
# instances = outputs["instances"]
|
| 192 |
+
# keypoints = instances.pred_keypoints.cpu().numpy().tolist() if instances.has("pred_keypoints") else None
|
| 193 |
+
|
| 194 |
+
# if not keypoints:
|
| 195 |
+
# return "No keypoints detected.", None
|
| 196 |
+
|
| 197 |
+
# # Save keypoints to JSON
|
| 198 |
+
# with open(output_file, "w") as f:
|
| 199 |
+
# json.dump({"keypoints": keypoints}, f, indent=4)
|
| 200 |
+
|
| 201 |
+
# keypoints = np.array(keypoints[0])[:, :2] # Extract (x, y) coordinates
|
| 202 |
+
|
| 203 |
+
# # COCO format indices
|
| 204 |
+
# NOSE, L_SHOULDER, R_SHOULDER = 0, 5, 6
|
| 205 |
+
# L_ELBOW, R_ELBOW = 7, 8
|
| 206 |
+
# L_WRIST, R_WRIST = 9, 10
|
| 207 |
+
# L_HIP, R_HIP = 11, 12
|
| 208 |
+
# L_ANKLE, R_ANKLE = 15, 16
|
| 209 |
+
|
| 210 |
+
# # Define Keypoint Pairs for Drawing Lines (COCO Format)
|
| 211 |
+
# skeleton = [(5, 6), (5, 11), (6, 12), (11, 12)]
|
| 212 |
+
|
| 213 |
+
# # Draw Keypoints
|
| 214 |
+
# for x, y in keypoints:
|
| 215 |
+
# cv2.circle(image, (int(x), int(y)), 5, (0, 255, 0), -1)
|
| 216 |
+
|
| 217 |
+
# # Draw Skeleton
|
| 218 |
+
# for pt1, pt2 in skeleton:
|
| 219 |
+
# x1, y1 = map(int, keypoints[pt1])
|
| 220 |
+
# x2, y2 = map(int, keypoints[pt2])
|
| 221 |
+
# cv2.line(image, (x1, y1), (x2, y2), (255, 0, 0), 2)
|
| 222 |
+
|
| 223 |
+
# # Function to calculate Euclidean distance
|
| 224 |
+
# def get_distance(p1, p2):
|
| 225 |
+
# return np.linalg.norm(np.array(p1) - np.array(p2))
|
| 226 |
+
|
| 227 |
+
# # Calculate full height (consider head length)
|
| 228 |
+
# ankle_mid = ((keypoints[L_ANKLE] + keypoints[R_ANKLE]) / 2).tolist()
|
| 229 |
+
# pixel_height = get_distance(keypoints[NOSE], ankle_mid)
|
| 230 |
+
|
| 231 |
+
# # Estimated full body height (add approx head length)
|
| 232 |
+
# estimated_full_pixel_height = pixel_height / 0.87 # Since 87% = nose to ankle
|
| 233 |
+
# pixels_per_cm = estimated_full_pixel_height / user_height_cm
|
| 234 |
+
|
| 235 |
+
# # Waist and shoulder measurements
|
| 236 |
+
# shoulder_width_px = get_distance(keypoints[L_SHOULDER], keypoints[R_SHOULDER])
|
| 237 |
+
# waist_width_px = get_distance(keypoints[L_HIP], keypoints[R_HIP])
|
| 238 |
+
|
| 239 |
+
# # Convert to cm
|
| 240 |
+
# shoulder_width_cm = shoulder_width_px / pixels_per_cm
|
| 241 |
+
# waist_width_cm = waist_width_px / pixels_per_cm
|
| 242 |
+
|
| 243 |
+
# # Torso Length (Neck to Pelvis)
|
| 244 |
+
# pelvis = ((keypoints[L_HIP] + keypoints[R_HIP]) / 2).tolist()
|
| 245 |
+
# neck = ((keypoints[L_SHOULDER] + keypoints[R_SHOULDER]) / 2).tolist()
|
| 246 |
+
# torso_length_px = get_distance(neck, pelvis)
|
| 247 |
+
# torso_length_cm = torso_length_px / pixels_per_cm
|
| 248 |
+
|
| 249 |
+
# # Arm Length (Shoulder to Wrist)
|
| 250 |
+
# arm_length_px = get_distance(keypoints[L_SHOULDER], keypoints[L_WRIST])
|
| 251 |
+
# arm_length_cm = arm_length_px / pixels_per_cm
|
| 252 |
+
|
| 253 |
+
# # Calculate waist and hip circumference (Ellipse approximation)
|
| 254 |
+
# # Waist circumference ≈ π × (waist_width / 2) × 2
|
| 255 |
+
# waist_circumference = np.pi * waist_width_cm
|
| 256 |
+
# hip_circumference = waist_circumference / 0.75 # Assuming hip is slightly bigger than waist
|
| 257 |
+
|
| 258 |
+
# # Improved body measurement calculation
|
| 259 |
+
# def calculate_body_measurements(waist_circumference, hip_circumference, shoulder_width_cm, torso_length_cm, arm_length_cm):
|
| 260 |
+
# return {
|
| 261 |
+
# "Waist Circumference (cm)": round(waist_circumference, 2),
|
| 262 |
+
# "Hip Circumference (cm)": round(hip_circumference, 2),
|
| 263 |
+
# "Shoulder Width (cm)": round(shoulder_width_cm, 2),
|
| 264 |
+
# "Torso Length (Neck to Pelvis, cm)": round(torso_length_cm, 2),
|
| 265 |
+
# "Full Arm Length (Shoulder to Wrist, cm)": round(arm_length_cm, 2),
|
| 266 |
+
# }
|
| 267 |
+
|
| 268 |
+
# measurements = calculate_body_measurements(waist_circumference, hip_circumference, shoulder_width_cm, torso_length_cm, arm_length_cm)
|
| 269 |
+
|
| 270 |
+
# return measurements, cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
# # Save to database function
|
| 274 |
+
# def save_to_database(measurements, image, user_height_cm):
|
| 275 |
+
# if measurements is None or image is None:
|
| 276 |
+
# return "No data to save."
|
| 277 |
+
|
| 278 |
+
# # Convert image to base64
|
| 279 |
+
# buffered = BytesIO()
|
| 280 |
+
# pil_image = Image.fromarray(image) # Convert to PIL Image from NumPy array
|
| 281 |
+
# pil_image.save(buffered, format="JPEG")
|
| 282 |
+
# img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
|
| 283 |
+
|
| 284 |
+
# # Send POST request to save measurements and image to the database
|
| 285 |
+
# response = requests.post(
|
| 286 |
+
# "https://9dbc-210-212-162-140.ngrok-free.app/upload", # Replace with your actual URL
|
| 287 |
+
# json={
|
| 288 |
+
# "imageBase64": img_str,
|
| 289 |
+
# "heightCm": user_height_cm,
|
| 290 |
+
# "waistCircumferenceCm": measurements["Waist Circumference (cm)"],
|
| 291 |
+
# "shoulderwidth": measurements["Shoulder Width (cm)"],
|
| 292 |
+
# "hipcircumference": measurements["Hip Circumference (cm)"],
|
| 293 |
+
# "torsolength": measurements["Torso Length (Neck to Pelvis, cm)"],
|
| 294 |
+
# "fullarmlength": measurements["Full Arm Length (Shoulder to Wrist, cm)"]
|
| 295 |
+
# }
|
| 296 |
+
# )
|
| 297 |
+
|
| 298 |
+
# return f"Status: {response.status_code}, Message: {response.text}"
|
| 299 |
+
|
| 300 |
+
# # Example usage (integrating with your Gradio app)
|
| 301 |
+
# import gradio as gr
|
| 302 |
+
|
| 303 |
+
# # Gradio interface setup
|
| 304 |
+
# def process_and_save(image, user_height_cm):
|
| 305 |
+
# measurements, processed_image = process_image(image, user_height_cm)
|
| 306 |
+
# if measurements:
|
| 307 |
+
# save_message = save_to_database(measurements, processed_image, user_height_cm)
|
| 308 |
+
# return processed_image, measurements, save_message
|
| 309 |
+
# else:
|
| 310 |
+
# return None, None, "Error in processing image."
|
| 311 |
+
|
| 312 |
+
# # Gradio interface setup
|
| 313 |
+
# iface = gr.Interface(
|
| 314 |
+
# fn=process_and_save,
|
| 315 |
+
# inputs=[gr.Image(type="numpy"), gr.Number(label="User Height (cm)")],
|
| 316 |
+
# outputs=[gr.Image(type="numpy"), gr.JSON(), gr.Textbox()],
|
| 317 |
+
# live=True
|
| 318 |
+
# )
|
| 319 |
+
|
| 320 |
+
# iface.launch(share=True)
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
import gradio as gr
|
| 325 |
import json
|
| 326 |
import base64
|
| 327 |
import requests
|
|
|
|
| 329 |
import torch
|
| 330 |
import numpy as np
|
| 331 |
import cv2
|
|
|
|
| 332 |
import os
|
| 333 |
+
from PIL import Image
|
| 334 |
+
from detectron2.engine import DefaultPredictor
|
| 335 |
+
from detectron2.config import get_cfg
|
| 336 |
from detectron2 import model_zoo
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 337 |
|
| 338 |
+
# === Set up Detectron2 model ===
|
| 339 |
cfg = get_cfg()
|
| 340 |
cfg.merge_from_file(model_zoo.get_config_file("COCO-Keypoints/keypoint_rcnn_R_50_FPN_3x.yaml"))
|
| 341 |
cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url("COCO-Keypoints/keypoint_rcnn_R_50_FPN_3x.yaml")
|
| 342 |
cfg.MODEL.DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
|
|
|
|
|
|
| 343 |
predictor = DefaultPredictor(cfg)
|
| 344 |
|
| 345 |
+
# === Utility ===
|
| 346 |
+
def get_distance(p1, p2):
|
| 347 |
+
return np.linalg.norm(np.array(p1) - np.array(p2))
|
|
|
|
|
|
|
|
|
|
| 348 |
|
| 349 |
+
# === Keypoint and Measurement Logic ===
|
| 350 |
+
def process_image(image, user_height_cm):
|
| 351 |
+
image_cv = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
|
| 352 |
+
outputs = predictor(image_cv)
|
| 353 |
instances = outputs["instances"]
|
| 354 |
keypoints = instances.pred_keypoints.cpu().numpy().tolist() if instances.has("pred_keypoints") else None
|
| 355 |
|
| 356 |
if not keypoints:
|
| 357 |
+
return "No keypoints detected.", None, None
|
|
|
|
|
|
|
|
|
|
|
|
|
| 358 |
|
| 359 |
+
keypoints = np.array(keypoints[0])[:, :2]
|
| 360 |
|
| 361 |
+
# Draw keypoints and skeleton
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 362 |
skeleton = [(5, 6), (5, 11), (6, 12), (11, 12)]
|
|
|
|
|
|
|
| 363 |
for x, y in keypoints:
|
| 364 |
+
cv2.circle(image_cv, (int(x), int(y)), 5, (0, 255, 0), -1)
|
|
|
|
|
|
|
| 365 |
for pt1, pt2 in skeleton:
|
| 366 |
x1, y1 = map(int, keypoints[pt1])
|
| 367 |
x2, y2 = map(int, keypoints[pt2])
|
| 368 |
+
cv2.line(image_cv, (x1, y1), (x2, y2), (255, 0, 0), 2)
|
| 369 |
|
| 370 |
+
# Body part indices
|
| 371 |
+
NOSE, L_SHOULDER, R_SHOULDER = 0, 5, 6
|
| 372 |
+
L_WRIST, L_HIP, R_HIP, L_ANKLE, R_ANKLE = 9, 11, 12, 15, 16
|
| 373 |
|
|
|
|
| 374 |
ankle_mid = ((keypoints[L_ANKLE] + keypoints[R_ANKLE]) / 2).tolist()
|
| 375 |
pixel_height = get_distance(keypoints[NOSE], ankle_mid)
|
| 376 |
+
estimated_full_pixel_height = pixel_height / 0.87
|
|
|
|
|
|
|
| 377 |
pixels_per_cm = estimated_full_pixel_height / user_height_cm
|
| 378 |
|
| 379 |
+
shoulder_width_cm = get_distance(keypoints[L_SHOULDER], keypoints[R_SHOULDER]) / pixels_per_cm
|
| 380 |
+
waist_width_cm = get_distance(keypoints[L_HIP], keypoints[R_HIP]) / pixels_per_cm
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 381 |
pelvis = ((keypoints[L_HIP] + keypoints[R_HIP]) / 2).tolist()
|
| 382 |
neck = ((keypoints[L_SHOULDER] + keypoints[R_SHOULDER]) / 2).tolist()
|
| 383 |
+
torso_length_cm = get_distance(neck, pelvis) / pixels_per_cm
|
| 384 |
+
arm_length_cm = get_distance(keypoints[L_SHOULDER], keypoints[L_WRIST]) / pixels_per_cm
|
|
|
|
|
|
|
|
|
|
|
|
|
| 385 |
|
|
|
|
|
|
|
| 386 |
waist_circumference = np.pi * waist_width_cm
|
| 387 |
+
hip_circumference = waist_circumference / 0.75
|
| 388 |
|
| 389 |
+
measurements = {
|
| 390 |
+
"Waist Circumference (cm)": round(waist_circumference, 2),
|
| 391 |
+
"Hip Circumference (cm)": round(hip_circumference, 2),
|
| 392 |
+
"Shoulder Width (cm)": round(shoulder_width_cm, 2),
|
| 393 |
+
"Torso Length (Neck to Pelvis, cm)": round(torso_length_cm, 2),
|
| 394 |
+
"Full Arm Length (Shoulder to Wrist, cm)": round(arm_length_cm, 2),
|
| 395 |
+
}
|
|
|
|
|
|
|
| 396 |
|
| 397 |
+
return measurements, cv2.cvtColor(image_cv, cv2.COLOR_BGR2RGB), keypoints.tolist()
|
| 398 |
|
| 399 |
+
# === Save to DB ===
|
| 400 |
+
def save_to_database(measurements, image, user_height_cm, user_id):
|
| 401 |
+
if not user_id:
|
| 402 |
+
return "❌ user_id missing from URL."
|
| 403 |
|
|
|
|
|
|
|
| 404 |
if measurements is None or image is None:
|
| 405 |
+
return "⚠️ No data to save."
|
| 406 |
|
|
|
|
| 407 |
buffered = BytesIO()
|
| 408 |
+
pil_image = Image.fromarray(image)
|
| 409 |
pil_image.save(buffered, format="JPEG")
|
| 410 |
img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
|
| 411 |
|
| 412 |
+
payload = {
|
| 413 |
+
"imageBase64": img_str,
|
| 414 |
+
"heightCm": user_height_cm,
|
| 415 |
+
"measurements": measurements
|
| 416 |
+
}
|
| 417 |
+
|
| 418 |
+
try:
|
| 419 |
+
response = requests.post(
|
| 420 |
+
f"https://9dbc-210-212-162-140.ngrok-free.app/upload/{user_id}",
|
| 421 |
+
json=payload
|
| 422 |
+
)
|
| 423 |
+
if response.status_code == 201:
|
| 424 |
+
return "✅ Measurements and image saved to database!"
|
| 425 |
+
else:
|
| 426 |
+
return f"❌ Failed: {response.status_code} - {response.text}"
|
| 427 |
+
except Exception as e:
|
| 428 |
+
return f"⚠️ Error during save: {str(e)}"
|
| 429 |
+
|
| 430 |
+
# === Gradio App ===
|
| 431 |
+
with gr.Blocks() as demo:
|
| 432 |
+
gr.Markdown("# ��� AI-Powered Body Measurement Tool")
|
| 433 |
+
user_id_state = gr.State()
|
| 434 |
+
|
| 435 |
+
@demo.load(inputs=None, outputs=[user_id_state])
|
| 436 |
+
def load_user_id(request: gr.Request):
|
| 437 |
+
return request.query_params.get("user_id", "")
|
| 438 |
+
|
| 439 |
+
with gr.Row():
|
| 440 |
+
with gr.Column():
|
| 441 |
+
image_input = gr.Image(label="Upload Your Full Body Image", type="pil")
|
| 442 |
+
height_input = gr.Number(label="Your Real Height (in cm)")
|
| 443 |
+
process_button = gr.Button("📐 Extract Measurements")
|
| 444 |
+
|
| 445 |
+
with gr.Column():
|
| 446 |
+
output_image = gr.Image(label="Detected Keypoints")
|
| 447 |
+
measurement_output = gr.JSON(label="Body Measurements")
|
| 448 |
+
|
| 449 |
+
with gr.Row():
|
| 450 |
+
save_button = gr.Button("💾 Save to Backend")
|
| 451 |
+
save_status = gr.Textbox(label="Status", interactive=False)
|
| 452 |
+
|
| 453 |
+
# Store results for save
|
| 454 |
+
processed_img = gr.State()
|
| 455 |
+
processed_data = gr.State()
|
| 456 |
+
|
| 457 |
+
process_button.click(
|
| 458 |
+
fn=process_image,
|
| 459 |
+
inputs=[image_input, height_input],
|
| 460 |
+
outputs=[measurement_output, output_image, processed_data]
|
| 461 |
+
).then(
|
| 462 |
+
fn=lambda img: img,
|
| 463 |
+
inputs=[output_image],
|
| 464 |
+
outputs=processed_img
|
| 465 |
)
|
| 466 |
|
| 467 |
+
save_button.click(
|
| 468 |
+
fn=save_to_database,
|
| 469 |
+
inputs=[measurement_output, processed_img, height_input, user_id_state],
|
| 470 |
+
outputs=save_status
|
| 471 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 472 |
|
| 473 |
+
if __name__ == "__main__":
|
| 474 |
+
demo.launch()
|