File size: 4,452 Bytes
2038252
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33278f3
2038252
 
 
 
33278f3
2038252
 
33278f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2038252
 
33278f3
2038252
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33278f3
 
2038252
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
import cv2
import mediapipe as mp
import numpy as np
import math
import os
from ultralytics import YOLO

class BodyMeasurement:
    def __init__(self, model_path="yolo11s-seg.pt"):
        self.model = YOLO(model_path)
        self.pose = mp.solutions.pose

    # ---------------- 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 ----
        mask = r.masks.data[0].cpu().numpy()
        mask = cv2.resize(mask, (img.shape[1], img.shape[0]))
        mask = (mask * 255).astype("uint8")

        # ---- segmented image ----
        mask3 = cv2.merge([mask, mask, mask])
        segmented = cv2.bitwise_and(img, mask3)

        # ---- FIND CONTOURS (boundary) ----
        contours, _ = cv2.findContours(
            mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
        )

        # ---- DRAW GREEN BOUNDARY ----
        cv2.drawContours(
            segmented,
            contours,
            -1,
            (0, 255, 0),   # green color
            3              # thickness
        )

        return segmented


    # ---------------- EDGE DETECTION -----------------
    def edges(self, rgb):
        gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY)
        gray = cv2.GaussianBlur(gray, (5,5), 0)
        edges = cv2.Canny(gray,50,150)
        return cv2.cvtColor(edges, cv2.COLOR_GRAY2RGB)

    # ---------------- 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)
                pts[self.pose.PoseLandmark(i).name] = (x,y)
        return pts

    # ---------------- 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,RS = G("LEFT_SHOULDER"), G("RIGHT_SHOULDER")
        LH,RH = G("LEFT_HIP"), G("RIGHT_HIP")
        LA,RA = G("LEFT_ANKLE"), G("RIGHT_ANKLE")
        nose = G("NOSE")

        if LS and RS: M["shoulder_px"] = self.dist(LS,RS)
        if LH and RH: M["hip_px"] = self.dist(LH,RH)

        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

        if height_cm:
            scale=height_cm/height_px
            M["scale_cm/px"]=scale
            if "shoulder_px" in M: M["shoulder_cm"]=M["shoulder_px"] * scale
            if "hip_px" in M: M["hip_cm"]=M["hip_px"] * scale

        return M

    # ---------------- PIPELINE -----------------
    def run(self, img_path, height_cm=None, output_folder="results"):
        if not os.path.exists(output_folder):
            os.makedirs(output_folder)

        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)
        edge=self.edges(rgb)
        pts=self.keypoints(rgb)
        M=self.measure(pts, rgb.shape[0], height_cm)

        overlay=cv2.addWeighted(rgb,0.7,edge,0.3,0)
        for x,y in pts.values():
            cv2.circle(overlay,(x,y),3,(0,255,0),-1)

        cv2.imwrite(f"{output_folder}/segmented.png", seg)
        cv2.imwrite(f"{output_folder}/edges.png", cv2.cvtColor(edge, cv2.COLOR_RGB2BGR))
        cv2.imwrite(f"{output_folder}/overlay.png", cv2.cvtColor(overlay, cv2.COLOR_RGB2BGR))

        print("\n Output Saved In Folder:", output_folder)
        print("Files:")
        print(" - segmented.png\n - edges.png\n - overlay.png")

        print("\n Measurements:")
        for k,v in M.items(): print(k,":",round(v,2))

        return M


# ---------------- RUN WITHOUT CLI -----------------
if __name__=="__main__":
    img_path = "/home/abhishek/Desktop/body_measurement /body_measurement/app/images/unnamed.jpg"            #  input image path dalen
    height_cm = 180                   # Optional (human actual height)
    output_folder = "Image_output"   # Output save directory

    BodyMeasurement().run(img_path, height_cm, output_folder)