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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Visualize canonical naming, side tags, and symmetry pairs across all datasets.
|
| 3 |
+
|
| 4 |
+
Produces:
|
| 5 |
+
1. Per-dataset skeleton with joints colored by side tag (L=red, R=blue, C=gray)
|
| 6 |
+
2. Canonical name labels on joints
|
| 7 |
+
3. Symmetry pairs connected by dashed lines
|
| 8 |
+
4. Cross-dataset canonical consistency heatmap
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import sys
|
| 12 |
+
import os
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
import numpy as np
|
| 15 |
+
import matplotlib
|
| 16 |
+
matplotlib.use('Agg')
|
| 17 |
+
import matplotlib.pyplot as plt
|
| 18 |
+
from mpl_toolkits.mplot3d import Axes3D
|
| 19 |
+
import matplotlib.patches as mpatches
|
| 20 |
+
|
| 21 |
+
project_root = Path(__file__).parent.parent
|
| 22 |
+
sys.path.insert(0, str(project_root))
|
| 23 |
+
|
| 24 |
+
from src.data.skeleton_graph import SkeletonGraph
|
| 25 |
+
from scripts.preprocess_bvh import forward_kinematics
|
| 26 |
+
|
| 27 |
+
RESULT_DIR = project_root / 'results' / 'canonical_check'
|
| 28 |
+
RESULT_DIR.mkdir(parents=True, exist_ok=True)
|
| 29 |
+
|
| 30 |
+
SIDE_COLORS = {'left': '#e74c3c', 'right': '#3498db', 'center': '#95a5a6'}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def plot_skeleton_canonical(ax, positions, parents, side_tags, canonical_names,
|
| 34 |
+
symmetry_pairs, title, label_fontsize=6):
|
| 35 |
+
"""Plot skeleton with side-colored joints and canonical name labels."""
|
| 36 |
+
J = len(parents)
|
| 37 |
+
pos = positions
|
| 38 |
+
|
| 39 |
+
# Draw bones
|
| 40 |
+
for j in range(J):
|
| 41 |
+
p = parents[j]
|
| 42 |
+
if p >= 0:
|
| 43 |
+
ax.plot3D([pos[j, 0], pos[p, 0]], [pos[j, 2], pos[p, 2]],
|
| 44 |
+
[pos[j, 1], pos[p, 1]], color='#bdc3c7', linewidth=1.5, zorder=1)
|
| 45 |
+
|
| 46 |
+
# Draw symmetry pairs as dashed lines
|
| 47 |
+
for i, j in symmetry_pairs:
|
| 48 |
+
if i < J and j < J:
|
| 49 |
+
mid_y = (pos[i, 1] + pos[j, 1]) / 2
|
| 50 |
+
ax.plot3D([pos[i, 0], pos[j, 0]], [pos[i, 2], pos[j, 2]],
|
| 51 |
+
[pos[i, 1], pos[j, 1]], color='#2ecc71', linewidth=0.8,
|
| 52 |
+
linestyle='--', alpha=0.5, zorder=2)
|
| 53 |
+
|
| 54 |
+
# Draw joints colored by side
|
| 55 |
+
for j in range(J):
|
| 56 |
+
color = SIDE_COLORS.get(side_tags[j], '#95a5a6')
|
| 57 |
+
ax.scatter3D([pos[j, 0]], [pos[j, 2]], [pos[j, 1]],
|
| 58 |
+
color=color, s=30, zorder=3, edgecolors='black', linewidths=0.3)
|
| 59 |
+
|
| 60 |
+
# Label joints with canonical names (subsample if too many)
|
| 61 |
+
step = max(1, J // 15)
|
| 62 |
+
for j in range(0, J, step):
|
| 63 |
+
ax.text(pos[j, 0], pos[j, 2], pos[j, 1] + 0.02,
|
| 64 |
+
canonical_names[j], fontsize=label_fontsize, ha='center', va='bottom',
|
| 65 |
+
color='black', alpha=0.8)
|
| 66 |
+
|
| 67 |
+
ax.set_title(title, fontsize=10, fontweight='bold')
|
| 68 |
+
ax.set_xlabel('X', fontsize=7)
|
| 69 |
+
ax.set_ylabel('Z', fontsize=7)
|
| 70 |
+
ax.set_zlabel('Y', fontsize=7)
|
| 71 |
+
ax.tick_params(labelsize=5)
|
| 72 |
+
|
| 73 |
+
# Equal axes
|
| 74 |
+
mid = pos.mean(axis=0)
|
| 75 |
+
span = max(pos.max(axis=0) - pos.min(axis=0)) / 2 + 0.05
|
| 76 |
+
ax.set_xlim(mid[0] - span, mid[0] + span)
|
| 77 |
+
ax.set_ylim(mid[2] - span, mid[2] + span)
|
| 78 |
+
ax.set_zlim(mid[1] - span, mid[1] + span)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def get_rest_pose(dataset_path, dataset_id):
|
| 82 |
+
"""Get rest pose joint positions from first motion."""
|
| 83 |
+
motions_dir = dataset_path / 'motions'
|
| 84 |
+
files = sorted(os.listdir(motions_dir))
|
| 85 |
+
if not files:
|
| 86 |
+
return None
|
| 87 |
+
d = dict(np.load(motions_dir / files[0], allow_pickle=True))
|
| 88 |
+
return d['joint_positions'][0] # first frame
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def visualize_human_datasets():
|
| 92 |
+
"""Plot 1: All 6 human datasets side by side."""
|
| 93 |
+
fig = plt.figure(figsize=(24, 8))
|
| 94 |
+
datasets = ['humanml3d', 'lafan1', '100style', 'bandai_namco', 'cmu_mocap', 'mixamo']
|
| 95 |
+
|
| 96 |
+
for idx, ds in enumerate(datasets):
|
| 97 |
+
ds_path = project_root / 'data' / 'processed' / ds
|
| 98 |
+
s = dict(np.load(ds_path / 'skeleton.npz', allow_pickle=True))
|
| 99 |
+
sg = SkeletonGraph.from_dict(s)
|
| 100 |
+
canon = [str(n) for n in s['canonical_names']]
|
| 101 |
+
rest_pos = get_rest_pose(ds_path, ds)
|
| 102 |
+
if rest_pos is None:
|
| 103 |
+
continue
|
| 104 |
+
|
| 105 |
+
ax = fig.add_subplot(1, 6, idx + 1, projection='3d')
|
| 106 |
+
plot_skeleton_canonical(
|
| 107 |
+
ax, rest_pos, sg.parent_indices, sg.side_tags, canon,
|
| 108 |
+
sg.symmetry_pairs,
|
| 109 |
+
f'{ds}\n{sg.num_joints}j, {len(sg.symmetry_pairs)} sym pairs',
|
| 110 |
+
label_fontsize=5 if sg.num_joints > 30 else 6,
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
# Legend
|
| 114 |
+
patches = [
|
| 115 |
+
mpatches.Patch(color=SIDE_COLORS['left'], label='Left'),
|
| 116 |
+
mpatches.Patch(color=SIDE_COLORS['right'], label='Right'),
|
| 117 |
+
mpatches.Patch(color=SIDE_COLORS['center'], label='Center'),
|
| 118 |
+
mpatches.Patch(color='#2ecc71', label='Symmetry pair'),
|
| 119 |
+
]
|
| 120 |
+
fig.legend(handles=patches, loc='lower center', ncol=4, fontsize=9)
|
| 121 |
+
|
| 122 |
+
plt.suptitle('Human Datasets — Canonical Names + Side Tags + Symmetry',
|
| 123 |
+
fontsize=14, fontweight='bold')
|
| 124 |
+
plt.tight_layout(rect=[0, 0.05, 1, 0.95])
|
| 125 |
+
out = RESULT_DIR / 'human_canonical_overview.png'
|
| 126 |
+
plt.savefig(out, dpi=150, bbox_inches='tight')
|
| 127 |
+
plt.close()
|
| 128 |
+
print(f'Saved: {out}')
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def visualize_zoo_animals():
|
| 132 |
+
"""Plot 2: Diverse Zoo animals with canonical names."""
|
| 133 |
+
species = ['Dog', 'Cat', 'Horse', 'Eagle', 'Trex', 'Spider',
|
| 134 |
+
'Ant', 'Anaconda', 'Dragon', 'Crab', 'Elephant', 'Bat']
|
| 135 |
+
fig = plt.figure(figsize=(24, 18))
|
| 136 |
+
|
| 137 |
+
zoo_path = project_root / 'data' / 'processed' / 'truebones_zoo'
|
| 138 |
+
motions_dir = zoo_path / 'motions'
|
| 139 |
+
|
| 140 |
+
# Find one motion per species
|
| 141 |
+
species_motions = {}
|
| 142 |
+
for f in sorted(os.listdir(motions_dir)):
|
| 143 |
+
d = dict(np.load(motions_dir / f, allow_pickle=True))
|
| 144 |
+
sp = str(d.get('species', ''))
|
| 145 |
+
if sp in species and sp not in species_motions:
|
| 146 |
+
species_motions[sp] = d
|
| 147 |
+
|
| 148 |
+
for idx, sp in enumerate(species):
|
| 149 |
+
if sp not in species_motions:
|
| 150 |
+
continue
|
| 151 |
+
d = species_motions[sp]
|
| 152 |
+
skel_path = zoo_path / 'skeletons' / f'{sp}.npz'
|
| 153 |
+
if not skel_path.exists():
|
| 154 |
+
continue
|
| 155 |
+
|
| 156 |
+
s = dict(np.load(skel_path, allow_pickle=True))
|
| 157 |
+
sg = SkeletonGraph.from_dict(s)
|
| 158 |
+
canon = [str(n) for n in s['canonical_names']]
|
| 159 |
+
rest_pos = d['joint_positions'][0]
|
| 160 |
+
|
| 161 |
+
ax = fig.add_subplot(3, 4, idx + 1, projection='3d')
|
| 162 |
+
plot_skeleton_canonical(
|
| 163 |
+
ax, rest_pos, sg.parent_indices, sg.side_tags, canon,
|
| 164 |
+
sg.symmetry_pairs,
|
| 165 |
+
f'{sp} ({sg.num_joints}j, {len(sg.symmetry_pairs)} sym)',
|
| 166 |
+
label_fontsize=5,
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
patches = [
|
| 170 |
+
mpatches.Patch(color=SIDE_COLORS['left'], label='Left'),
|
| 171 |
+
mpatches.Patch(color=SIDE_COLORS['right'], label='Right'),
|
| 172 |
+
mpatches.Patch(color=SIDE_COLORS['center'], label='Center'),
|
| 173 |
+
mpatches.Patch(color='#2ecc71', label='Symmetry pair'),
|
| 174 |
+
]
|
| 175 |
+
fig.legend(handles=patches, loc='lower center', ncol=4, fontsize=10)
|
| 176 |
+
|
| 177 |
+
plt.suptitle('Truebones Zoo — Canonical Names + Side Tags + Symmetry',
|
| 178 |
+
fontsize=14, fontweight='bold')
|
| 179 |
+
plt.tight_layout(rect=[0, 0.04, 1, 0.96])
|
| 180 |
+
out = RESULT_DIR / 'zoo_canonical_overview.png'
|
| 181 |
+
plt.savefig(out, dpi=150, bbox_inches='tight')
|
| 182 |
+
plt.close()
|
| 183 |
+
print(f'Saved: {out}')
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def visualize_cross_dataset_consistency():
|
| 187 |
+
"""Plot 3: Heatmap showing canonical name consistency across datasets."""
|
| 188 |
+
# Collect canonical names for core body parts across datasets
|
| 189 |
+
core_parts = [
|
| 190 |
+
'pelvis', 'spine lower', 'spine mid', 'spine upper', 'neck', 'head',
|
| 191 |
+
'left collar', 'left upper arm', 'left forearm', 'left hand',
|
| 192 |
+
'right collar', 'right upper arm', 'right forearm', 'right hand',
|
| 193 |
+
'left upper leg', 'left lower leg', 'left foot', 'left toe',
|
| 194 |
+
'right upper leg', 'right lower leg', 'right foot', 'right toe',
|
| 195 |
+
]
|
| 196 |
+
|
| 197 |
+
datasets = ['humanml3d', 'lafan1', '100style', 'bandai_namco', 'cmu_mocap', 'mixamo']
|
| 198 |
+
matrix = np.zeros((len(core_parts), len(datasets)), dtype=np.float32)
|
| 199 |
+
|
| 200 |
+
for j, ds in enumerate(datasets):
|
| 201 |
+
s = dict(np.load(f'data/processed/{ds}/skeleton.npz', allow_pickle=True))
|
| 202 |
+
canon_set = set(str(n) for n in s['canonical_names'])
|
| 203 |
+
for i, part in enumerate(core_parts):
|
| 204 |
+
matrix[i, j] = 1.0 if part in canon_set else 0.0
|
| 205 |
+
|
| 206 |
+
fig, ax = plt.subplots(figsize=(10, 12))
|
| 207 |
+
im = ax.imshow(matrix, cmap='RdYlGn', aspect='auto', vmin=0, vmax=1)
|
| 208 |
+
|
| 209 |
+
ax.set_xticks(range(len(datasets)))
|
| 210 |
+
ax.set_xticklabels(datasets, rotation=45, ha='right', fontsize=9)
|
| 211 |
+
ax.set_yticks(range(len(core_parts)))
|
| 212 |
+
ax.set_yticklabels(core_parts, fontsize=9)
|
| 213 |
+
|
| 214 |
+
# Annotate cells
|
| 215 |
+
for i in range(len(core_parts)):
|
| 216 |
+
for j in range(len(datasets)):
|
| 217 |
+
text = '✓' if matrix[i, j] > 0.5 else '✗'
|
| 218 |
+
color = 'white' if matrix[i, j] > 0.5 else 'red'
|
| 219 |
+
ax.text(j, i, text, ha='center', va='center', fontsize=10, color=color)
|
| 220 |
+
|
| 221 |
+
ax.set_title('Cross-Dataset Canonical Name Coverage\n(22 core human body parts)',
|
| 222 |
+
fontsize=12, fontweight='bold')
|
| 223 |
+
plt.colorbar(im, ax=ax, label='Present in dataset', shrink=0.6)
|
| 224 |
+
plt.tight_layout()
|
| 225 |
+
out = RESULT_DIR / 'canonical_consistency_heatmap.png'
|
| 226 |
+
plt.savefig(out, dpi=150, bbox_inches='tight')
|
| 227 |
+
plt.close()
|
| 228 |
+
print(f'Saved: {out}')
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def visualize_side_tag_stats():
|
| 232 |
+
"""Plot 4: Bar chart of side tag distribution per dataset."""
|
| 233 |
+
all_data = []
|
| 234 |
+
labels = []
|
| 235 |
+
|
| 236 |
+
datasets = ['humanml3d', 'lafan1', '100style', 'bandai_namco', 'cmu_mocap', 'mixamo']
|
| 237 |
+
for ds in datasets:
|
| 238 |
+
s = dict(np.load(f'data/processed/{ds}/skeleton.npz', allow_pickle=True))
|
| 239 |
+
sg = SkeletonGraph.from_dict(s)
|
| 240 |
+
n_l = sum(1 for t in sg.side_tags if t == 'left')
|
| 241 |
+
n_r = sum(1 for t in sg.side_tags if t == 'right')
|
| 242 |
+
n_c = sum(1 for t in sg.side_tags if t == 'center')
|
| 243 |
+
all_data.append((n_l, n_r, n_c, len(sg.symmetry_pairs)))
|
| 244 |
+
labels.append(f'{ds}\n({sg.num_joints}j)')
|
| 245 |
+
|
| 246 |
+
# Add Zoo species
|
| 247 |
+
for sp in ['Dog', 'Cat', 'Horse', 'Eagle', 'Trex', 'Spider', 'Anaconda', 'Dragon']:
|
| 248 |
+
s = dict(np.load(f'data/processed/truebones_zoo/skeletons/{sp}.npz', allow_pickle=True))
|
| 249 |
+
sg = SkeletonGraph.from_dict(s)
|
| 250 |
+
n_l = sum(1 for t in sg.side_tags if t == 'left')
|
| 251 |
+
n_r = sum(1 for t in sg.side_tags if t == 'right')
|
| 252 |
+
n_c = sum(1 for t in sg.side_tags if t == 'center')
|
| 253 |
+
all_data.append((n_l, n_r, n_c, len(sg.symmetry_pairs)))
|
| 254 |
+
labels.append(f'{sp}\n({sg.num_joints}j)')
|
| 255 |
+
|
| 256 |
+
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(16, 10))
|
| 257 |
+
|
| 258 |
+
x = range(len(labels))
|
| 259 |
+
lefts = [d[0] for d in all_data]
|
| 260 |
+
rights = [d[1] for d in all_data]
|
| 261 |
+
centers = [d[2] for d in all_data]
|
| 262 |
+
syms = [d[3] for d in all_data]
|
| 263 |
+
|
| 264 |
+
ax1.bar(x, lefts, color=SIDE_COLORS['left'], label='Left', alpha=0.8)
|
| 265 |
+
ax1.bar(x, rights, bottom=lefts, color=SIDE_COLORS['right'], label='Right', alpha=0.8)
|
| 266 |
+
ax1.bar(x, centers, bottom=[l+r for l,r in zip(lefts, rights)],
|
| 267 |
+
color=SIDE_COLORS['center'], label='Center', alpha=0.8)
|
| 268 |
+
ax1.set_xticks(x)
|
| 269 |
+
ax1.set_xticklabels(labels, fontsize=8)
|
| 270 |
+
ax1.set_ylabel('Joint Count')
|
| 271 |
+
ax1.set_title('Side Tag Distribution per Dataset/Species', fontweight='bold')
|
| 272 |
+
ax1.legend()
|
| 273 |
+
ax1.axvline(x=5.5, color='black', linestyle='--', alpha=0.3)
|
| 274 |
+
ax1.text(2.5, max(lefts)*2.5, 'Human', ha='center', fontsize=10, style='italic')
|
| 275 |
+
ax1.text(9.5, max(lefts)*2.5, 'Zoo Animals', ha='center', fontsize=10, style='italic')
|
| 276 |
+
|
| 277 |
+
ax2.bar(x, syms, color='#2ecc71', alpha=0.8)
|
| 278 |
+
ax2.set_xticks(x)
|
| 279 |
+
ax2.set_xticklabels(labels, fontsize=8)
|
| 280 |
+
ax2.set_ylabel('Symmetry Pairs')
|
| 281 |
+
ax2.set_title('Detected Symmetry Pairs per Dataset/Species', fontweight='bold')
|
| 282 |
+
ax2.axvline(x=5.5, color='black', linestyle='--', alpha=0.3)
|
| 283 |
+
|
| 284 |
+
plt.tight_layout()
|
| 285 |
+
out = RESULT_DIR / 'side_tag_stats.png'
|
| 286 |
+
plt.savefig(out, dpi=150, bbox_inches='tight')
|
| 287 |
+
plt.close()
|
| 288 |
+
print(f'Saved: {out}')
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
if __name__ == '__main__':
|
| 292 |
+
print('Generating canonical name visualizations...\n')
|
| 293 |
+
visualize_human_datasets()
|
| 294 |
+
visualize_zoo_animals()
|
| 295 |
+
visualize_cross_dataset_consistency()
|
| 296 |
+
visualize_side_tag_stats()
|
| 297 |
+
print(f'\nAll saved to: {RESULT_DIR}/')
|