# import cv2 # import mediapipe as mp # import numpy as np # import math # import os # import csv # from ultralytics import YOLO # class BodyMeasurement: # def __init__(self, model_path="yolo11s-seg.pt"): # self.model = YOLO(model_path) # self.pose = mp.solutions.pose # self.last_mask = None # self.last_contours = None # # ---------------- PERSON SEGMENTATION ----------------- # def segment(self, img): # results = self.model(img, verbose=False) # r = results[0] # if r.masks is None: # print("❌ No person detected!") # return img # mask = r.masks.data[0].cpu().numpy() # mask = cv2.resize(mask, (img.shape[1], img.shape[0])) # mask = (mask * 255).astype("uint8") # self.last_mask = mask # mask3 = cv2.merge([mask, mask, mask]) # segmented = cv2.bitwise_and(img, mask3) # contours, _ = cv2.findContours( # mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE # ) # self.last_contours = contours # cv2.drawContours(segmented, contours, -1, (0, 255, 0), 3) # return segmented # # ---------------- MEDIAPIPE KEYPOINTS ----------------- # def keypoints(self, rgb): # h, w, _ = rgb.shape # pts = {} # with self.pose.Pose(static_image_mode=True) as p: # res = p.process(rgb) # if not res.pose_landmarks: # return pts # for i, lm in enumerate(res.pose_landmarks.landmark): # x, y = int(lm.x * w), int(lm.y * h) # name = self.pose.PoseLandmark(i).name # pts[name] = (x, y) # return pts # # ---------------- BODY BORDER COORDINATES ----------------- # def get_body_border_coordinates(self): # if self.last_contours is None: # return [] # body_contour = max(self.last_contours, key=cv2.contourArea) # border_points = [] # for pt in body_contour: # x, y = pt[0] # border_points.append((int(x), int(y))) # return border_points # # ---------------- DRAW BORDER COORDINATES ----------------- # def draw_border_points_with_coords(self, img, border_points, step=40): # for i, (x, y) in enumerate(border_points): # if i % step != 0: # continue # cv2.circle(img, (x, y), 3, (255, 0, 255), -1) # cv2.putText( # img, # f"({x},{y})", # (x + 4, y - 4), # cv2.FONT_HERSHEY_SIMPLEX, # 0.35, # (255, 0, 255), # 1 # ) # # ---------------- DRAW MEDIAPIPE POINTS ----------------- # def draw_mediapipe_points(self, img, pts): # for name, (x, y) in pts.items(): # cv2.circle(img, (x, y), 4, (0, 255, 0), -1) # cv2.putText( # img, # f"{name[:2]}({x},{y})", # (x + 4, y - 4), # cv2.FONT_HERSHEY_SIMPLEX, # 0.35, # (0, 255, 0), # 1 # ) # # ---------------- PROJECTION TO BODY BOUNDARY ----------------- # def project_to_boundary_x(self, mask, x, y, direction): # h, w = mask.shape # rng = range(x, 0, -1) if direction == "left" else range(x, w) # for cx in rng: # if mask[y, cx] > 0: # return (cx, y) # return None # # ---------------- MEASUREMENTS ----------------- # def dist(self, a, b): # return math.dist(a, b) # def measure(self, pts, img_h, height_cm=None): # M = {} # G = lambda k: pts.get(k) # LS = G("LEFT_SHOULDER") # RS = G("RIGHT_SHOULDER") # LA = G("LEFT_ANKLE") # RA = G("RIGHT_ANKLE") # nose = G("NOSE") # if nose and LA and RA: # mid = ((LA[0] + RA[0]) // 2, (LA[1] + RA[1]) // 2) # height_px = self.dist(nose, mid) # else: # height_px = img_h # M["height_px"] = height_px # mask = self.last_mask # if mask is not None and LS and RS: # Lb = self.project_to_boundary_x(mask, LS[0], LS[1], "left") # Rb = self.project_to_boundary_x(mask, RS[0], RS[1], "right") # if Lb and Rb: # shoulder_px = self.dist(Lb, Rb) # M["shoulder_px"] = shoulder_px # M["shoulder_boundary"] = (Lb, Rb) # if height_cm: # scale = height_cm / height_px # M["scale_cm_per_px"] = scale # if "shoulder_px" in M: # M["shoulder_cm"] = M["shoulder_px"] * scale # return M # # ---------------- PIPELINE ----------------- # def run(self, img_path, height_cm=None, output_folder="results"): # os.makedirs(output_folder, exist_ok=True) # img = cv2.imread(img_path) # if img is None: # raise FileNotFoundError("❌ Image not found!") # seg = self.segment(img) # rgb = cv2.cvtColor(seg, cv2.COLOR_BGR2RGB) # pts = self.keypoints(rgb) # M = self.measure(pts, rgb.shape[0], height_cm) # overlay = rgb.copy() # # Draw segmentation border coordinates # border_coords = self.get_body_border_coordinates() # self.draw_border_points_with_coords(overlay, border_coords, step=40) # # Draw MediaPipe coordinates # self.draw_mediapipe_points(overlay, pts) # # Draw shoulder measurement # if "shoulder_boundary" in M: # Lb, Rb = M["shoulder_boundary"] # cv2.circle(overlay, Lb, 6, (0, 0, 255), -1) # cv2.circle(overlay, Rb, 6, (0, 0, 255), -1) # cv2.line(overlay, Lb, Rb, (255, 0, 0), 2) # cv2.putText( # overlay, # f"Shoulder: {round(M['shoulder_cm'],2)} cm", # (20, 40), # cv2.FONT_HERSHEY_SIMPLEX, # 0.9, # (255, 0, 0), # 2 # ) # # Save images # cv2.imwrite(f"{output_folder}/segmented.png", seg) # cv2.imwrite( # f"{output_folder}/overlay.png", # cv2.cvtColor(overlay, cv2.COLOR_RGB2BGR) # ) # # Save CSV # with open(f"{output_folder}/body_border_coordinates.csv", "w", newline="") as f: # writer = csv.writer(f) # writer.writerow(["x", "y"]) # for x, y in border_coords: # writer.writerow([x, y]) # print("✅ DONE") # print("Border points:", len(border_coords)) # return M # # ---------------- RUN ----------------- # if __name__ == "__main__": # BASE_DIR = os.path.dirname(os.path.abspath(__file__)) # img_path = os.path.abspath(os.path.join(BASE_DIR, "..", "images", "unnamed.jpg")) # height_cm = 180 # output_folder = "Image_output" # BodyMeasurement().run(img_path, height_cm, output_folder) import cv2 import mediapipe as mp import numpy as np import math import os import csv from ultralytics import YOLO class BodyMeasurement: def __init__(self, model_path="yolo11s-seg.pt"): self.model = YOLO(model_path) self.pose = mp.solutions.pose self.last_mask = None self.landmarks = None # ---------------- PERSON SEGMENTATION ----------------- def segment(self, img): r = self.model(img, verbose=False)[0] if r.masks is None: raise ValueError("❌ No person detected") mask = r.masks.data[0].cpu().numpy() mask = cv2.resize(mask, (img.shape[1], img.shape[0])) self.last_mask = (mask * 255).astype("uint8") return cv2.bitwise_and(img, cv2.merge([self.last_mask]*3)) # ---------------- HEIGHT & LANDMARKS ----------------- def get_height_px(self, rgb): h, w, _ = rgb.shape with self.pose.Pose(static_image_mode=True) as p: res = p.process(rgb) if not res.pose_landmarks: return h, None lm = res.pose_landmarks.landmark self.landmarks = lm nose = (lm[0].x * w, lm[0].y * h) foot = ((lm[27].x + lm[28].x) * w / 2, (lm[27].y + lm[28].y) * h / 2) return math.dist(nose, foot), lm # ---------------- ARM-AWARE WIDTH DETECTION ----------------- def get_body_width_v2(self, y, band=20): """ Advanced method: Uses MediaPipe shoulder/hip landmarks to estimate body center and torso width WITHOUT arms """ mask = self.last_mask h, w = mask.shape if self.landmarks is None: return None lm = self.landmarks # Get shoulder and hip x-coordinates left_shoulder_x = lm[11].x * w right_shoulder_x = lm[12].x * w left_hip_x = lm[23].x * w right_hip_x = lm[24].x * w # Body center center_x = (left_shoulder_x + right_shoulder_x) / 2 # Torso skeleton width (shoulder to shoulder OR hip to hip) shoulder_width = abs(right_shoulder_x - left_shoulder_x) hip_width = abs(right_hip_x - left_hip_x) # Use appropriate width based on measurement level shoulders_y = (lm[11].y + lm[12].y) / 2 * h hips_y = (lm[23].y + lm[24].y) / 2 * h # If measuring near shoulders, use shoulder width; near hips, use hip width if abs(y - shoulders_y) < abs(y - hips_y): base_width = shoulder_width else: base_width = hip_width # Expected torso width = skeleton width + small margin (NOT 1.2x!) expected_torso_width = base_width * 1.05 # Only 5% margin widths = [] for dy in range(-band, band + 1): yy = y + dy if yy < 0 or yy >= h: continue xs = np.where(mask[yy] > 0)[0] if len(xs) < 20: continue # Find pixels near body center (tight bounds) left_bound = center_x - expected_torso_width / 2 right_bound = center_x + expected_torso_width / 2 # Filter only torso pixels (exclude arms) torso_xs = xs[(xs >= left_bound) & (xs <= right_bound)] if len(torso_xs) > 10: width = torso_xs[-1] - torso_xs[0] widths.append(width) return int(np.median(widths)) if widths else None # ---------------- FALLBACK: CONTOUR-BASED WIDTH ----------------- def get_body_width_contour(self, y, band=10): """ Use contours to find the main body and exclude arms More aggressive arm removal """ mask = self.last_mask h, w = mask.shape # Extract region of interest y1 = max(0, y - band) y2 = min(h, y + band) roi = mask[y1:y2, :] # Find contours contours, _ = cv2.findContours(roi, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) if not contours: return None # Get largest contour (main body) largest_contour = max(contours, key=cv2.contourArea) # For each row in band, find width widths = [] for dy in range(band * 2): yy = dy if yy >= roi.shape[0]: continue xs = np.where(roi[yy] > 0)[0] if len(xs) < 20: continue # Keep only center 60% to exclude arms (more aggressive) keep_start = int(len(xs) * 0.20) keep_end = int(len(xs) * 0.80) xs_center = xs[keep_start:keep_end] if len(xs_center) > 5: widths.append(xs_center[-1] - xs_center[0]) return int(np.median(widths)) if widths else None # ---------------- DYNAMIC MEASUREMENT LEVELS ----------------- def get_measurement_levels(self, rgb): """Use MediaPipe landmarks to find accurate body positions""" h, w = rgb.shape[:2] if self.landmarks is None: return { "chest": int(h * 0.28), "waist": int(h * 0.48), "hip": int(h * 0.58) } lm = self.landmarks # Use actual body landmarks shoulders_y = (lm[11].y + lm[12].y) / 2 * h hips_y = (lm[23].y + lm[24].y) / 2 * h # Calculate positions chest_y = int(shoulders_y + (hips_y - shoulders_y) * 0.20) waist_y = int(shoulders_y + (hips_y - shoulders_y) * 0.75) hip_y = int(hips_y + 10) # Slightly below hip landmark return { "chest": chest_y, "waist": waist_y, "hip": hip_y } # ---------------- CIRCUMFERENCE CALCULATION ----------------- def calculate_circumference(self, width_px, scale, body_part): """ Calculate circumference from width using proper depth estimation Key insight: Body depth (front-to-back) is NOT equal to width - Chest depth ≈ 50% of width - Waist depth ≈ 40% of width - Hip depth ≈ 45% of width """ # Depth ratios (depth/width) depth_ratios = { "chest": 0.52, "waist": 0.42, "hip": 0.48 } depth_ratio = depth_ratios.get(body_part, 0.45) # Ellipse circumference approximation (Ramanujan) # C ≈ π × (3(a+b) - sqrt((3a+b)(a+3b))) # where a = width/2, b = depth/2 a = width_px / 2 # semi-major axis (width) b = (width_px * depth_ratio) / 2 # semi-minor axis (depth) # Simplified Ramanujan approximation circumference = math.pi * (3 * (a + b) - math.sqrt((3*a + b) * (a + 3*b))) # Convert to cm return circumference * scale # ---------------- MEASURE ----------------- def measure(self, rgb, height_cm): img_h = rgb.shape[0] height_px, _ = self.get_height_px(rgb) scale = height_cm / height_px M = { "scale": round(scale, 4), "height_cm": height_cm, "height_px": round(height_px, 2) } levels = self.get_measurement_levels(rgb) for name, y in levels.items(): # Try landmark-based method first width_px = self.get_body_width_v2(y, band=20) # Fallback to contour method if width_px is None or width_px < 50: width_px = self.get_body_width_contour(y, band=15) if not width_px or width_px < 50: print(f"⚠️ Could not measure {name}") continue circumference = self.calculate_circumference(width_px, scale, name) M[name] = round(circumference, 2) M[name+"_y"] = y M[name+"_width_px"] = width_px return M # ---------------- DRAW WITH DEBUG INFO ----------------- def draw(self, img, M): colors = { "chest": (0, 255, 255), "waist": (255, 0, 255), "hip": (0, 255, 0) } # Draw skeleton if available if self.landmarks: h, w = img.shape[:2] lm = self.landmarks # Draw shoulder and hip landmarks for idx in [11, 12, 23, 24]: x = int(lm[idx].x * w) y = int(lm[idx].y * h) cv2.circle(img, (x, y), 5, (255, 255, 255), -1) for k in ["chest", "waist", "hip"]: if k in M: y = M[k+"_y"] color = colors[k] cv2.line(img, (50, y), (img.shape[1]-50, y), color, 3) text = f"{k.upper()}: {M[k]} cm" cv2.putText(img, text, (60, y-15), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2) # ---------------- RUN ----------------- def run(self, img_path, height_cm, out="results"): os.makedirs(out, exist_ok=True) img = cv2.imread(img_path) if img is None: raise FileNotFoundError("Image not found") seg = self.segment(img) rgb = cv2.cvtColor(seg, cv2.COLOR_BGR2RGB) M = self.measure(rgb, height_cm) overlay = rgb.copy() self.draw(overlay, M) # Save debug visualization cv2.imwrite(f"{out}/final.png", cv2.cvtColor(overlay, cv2.COLOR_RGB2BGR)) # Save mask for debugging cv2.imwrite(f"{out}/mask_debug.png", self.last_mask) with open(f"{out}/measurements.csv", "w", newline="") as f: w = csv.writer(f) w.writerow(["Part", "cm", "pixels_width"]) for k in ["chest", "waist", "hip"]: if k in M: w.writerow([k, M[k], M.get(k+"_width_px", "")]) print("\n✅ FINAL MEASUREMENTS") print(f"📏 Height: {height_cm} cm (Scale: {M['scale']} cm/px)") print("-" * 40) for k in ["chest", "waist", "hip"]: if k in M: print(f"{k.capitalize():8} : {M[k]:6.2f} cm (width: {M.get(k+'_width_px', 0)} px)") # Sanity check print("\n🔍 SANITY CHECK:") if "chest" in M and "waist" in M: if M["waist"] > M["chest"] * 1.3: print("⚠️ WARNING: Waist seems too large compared to chest!") if "hip" in M and "waist" in M: if M["hip"] < M["waist"]: print("⚠️ WARNING: Hip should typically be larger than waist!") return M # ---------------- RUN ----------------- if __name__ == "__main__": BASE_DIR = os.path.dirname(os.path.abspath(__file__)) img = os.path.join(BASE_DIR, "..", "images", "unnamed.jpg") BodyMeasurement().run(img, height_cm=180, out="Image_output")