Spaces:
Runtime error
Runtime error
File size: 5,442 Bytes
85adc6e | 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 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 | import mediapipe as mp
import numpy as np
import matplotlib.pyplot as plt
import streamlit as st
import plotly.graph_objects as go
import matplotlib
import pandas as pd
from PIL import Image
st.title("๋ค๋ฐฉ๋ฉด ์ด๋ฏธ์ง ๊ธฐ๋ฐ ์์ธ ์๊ฐํ")
front_image = st.file_uploader("์", type=['png', 'jpg', 'jpeg'])
left_image = st.file_uploader("์ผ์ชฝ", type=['png', 'jpg', 'jpeg'])
right_image = st.file_uploader("์ค๋ฅธ์ชฝ", type=['png', 'jpg', 'jpeg'])
back_image = st.file_uploader("๋ค", type=['png', 'jpg', 'jpeg'])
# Mediapipe ์ด๊ธฐํ
mp_pose = mp.solutions.pose
mp_indices = {landmark.name: landmark.value for landmark in mp_pose.PoseLandmark}
# ํฌ์ฆ ์ฐ๊ฒฐ์
connections = [
("LEFT_SHOULDER", "RIGHT_SHOULDER"),
("LEFT_SHOULDER", "LEFT_ELBOW"), ("LEFT_ELBOW", "LEFT_WRIST"),
("RIGHT_SHOULDER", "RIGHT_ELBOW"), ("RIGHT_ELBOW", "RIGHT_WRIST"),
("RIGHT_WRIST", "RIGHT_THUMB"), ("RIGHT_WRIST", "RIGHT_INDEX"),
("RIGHT_WRIST", "RIGHT_PINKY"), ("RIGHT_INDEX", "RIGHT_PINKY"),
("LEFT_WRIST", "LEFT_THUMB"), ("LEFT_WRIST", "LEFT_INDEX"),
("LEFT_WRIST", "LEFT_PINKY"), ("LEFT_INDEX", "LEFT_PINKY"),
("LEFT_HIP", "RIGHT_HIP"),
("LEFT_SHOULDER", "LEFT_HIP"), ("RIGHT_SHOULDER", "RIGHT_HIP"),
("LEFT_HIP", "LEFT_KNEE"), ("LEFT_KNEE", "LEFT_ANKLE"),
("RIGHT_HIP", "RIGHT_KNEE"), ("RIGHT_KNEE", "RIGHT_ANKLE"),
("RIGHT_ANKLE", "RIGHT_FOOT_INDEX"), ("LEFT_ANKLE", "LEFT_FOOT_INDEX"),
("RIGHT_ANKLE", "RIGHT_HEEL"), ("LEFT_ANKLE", "LEFT_HEEL"),
("RIGHT_FOOT_INDEX", "RIGHT_HEEL"), ("LEFT_FOOT_INDEX", "LEFT_HEEL"),
]
# ํ์ ํจ์
def rotate_y(points, angle_deg):
angle = np.radians(angle_deg)
cos_a = np.cos(angle)
sin_a = np.sin(angle)
R = np.array([
[cos_a, 0, sin_a],
[0, 1, 0],
[-sin_a, 0, cos_a]
])
return points @ R.T
# Mediapipe ํฌ์ฆ ์ถ์ถ
def get_pose_landmarks(image_file):
if image_file is None:
return None
image = Image.open(image_file).convert("RGB")
image_np = np.array(image)
h, w = image_np.shape[:2]
with mp_pose.Pose(static_image_mode=True, model_complexity=2) as pose:
result = pose.process(image_np)
if result.pose_landmarks:
landmarks = result.pose_landmarks.landmark
return np.array([[lm.x * w, lm.y * h, lm.z, lm.visibility] for lm in landmarks])
else:
return None
# ์ด๋ฏธ์ง ๊ฒฝ๋ก
dir_path = "/home/arica/Documents/pose estimation/04_3Dpose_๋ค๋ฐฉํฅ/data/"
image_paths = {
'front': front_image,
'left': left_image,
'right': right_image,
'back': back_image
}
# ๋ฐฉํฅ๋ณ ํ์ ๊ฐ๋
rotation_angles = {
'front': 0,
'left': -90,
'right': 90,
'back': 180,
}
# Z ๋ณด์ ๊ณ์
# z_scale = 0.5
# ๋ฐฉํฅ๋ณ ๋๋๋งํฌ ์ถ์ถ ๋ฐ ํ์ ์ ์ฉ
landmarks_dict = {}
for direction, path in image_paths.items():
lm = get_pose_landmarks(path)
if lm is not None:
rotated = rotate_y(lm[:, :3], rotation_angles[direction])
# rotated[:, 2] *= z_scale
landmarks_dict[direction] = {
"coords": rotated,
"visibility": lm[:, 3]
}
else:
print(f"[๊ฒฝ๊ณ ] {direction} ์ด๋ฏธ์ง์์ ๋๋๋งํฌ๋ฅผ ์ถ์ถํ์ง ๋ชปํ์ต๋๋ค.")
# ๊ฐ์ค ํ๊ท ๊ณ์ฐ
all_landmarks = []
for i in range(33):
points = []
weights = []
for direction in landmarks_dict:
points.append(landmarks_dict[direction]["coords"][i])
weights.append(landmarks_dict[direction]["visibility"][i])
if np.sum(weights) > 0:
avg = np.average(points, axis=0, weights=weights)
else:
avg = [0, 0, 0]
all_landmarks.append(avg)
all_landmarks = np.array(all_landmarks)
if back_image is not None:
df = pd.DataFrame(all_landmarks, columns=['x', 'y', 'z'])
df.insert(loc=1, column='landmarkType', value=mp_indices.keys())
print(df)
fig = go.Figure()
fig.add_trace(go.Scatter3d(
x=df["x"],
y=df["y"],
z=df["z"],
mode='markers',
marker=dict(size=5, color='blue'),
text=df["landmarkType"]
))
for a, b in connections:
try:
xa, ya, za = df[df["landmarkType"] == a][["x", "y", "z"]].values[0]
xb, yb, zb = df[df["landmarkType"] == b][["x", "y", "z"]].values[0]
fig.add_trace(go.Scatter3d(
x=[xa, xb],
y=[ya, yb],
z=[za, zb],
mode='lines',
line=dict(color='green', width=3)
))
except IndexError:
continue
fig.update_layout(
scene=dict(
xaxis_title='X',
yaxis_title='Y',
zaxis_title='Z',
aspectmode='data'
),
margin=dict(l=0, r=0, b=0, t=0)
)
st.text('3D')
st.plotly_chart(fig, use_container_width=True)
st.text('2D')
fig, ax = plt.subplots(figsize=(6, 8))
for a, b in connections:
try:
xa, ya = df[df["landmarkType"] == a][["x", "y"]].values[0]
xb, yb = df[df["landmarkType"] == b][["x", "y"]].values[0]
ax.plot([xa, xb], [ya, yb], color='green')
except IndexError:
continue
ax.scatter(df["x"], df["y"], c="blue")
ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_title("2D Pose")
ax.set_aspect('equal')
ax.invert_yaxis()
plt.tight_layout()
st.pyplot(fig)
|