MultiViewPose / app.py
simba12343's picture
Update app.py
58ebffa verified
Raw History Blame Contribute Delete
5.44 kB
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)