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)