File size: 11,749 Bytes
d92f981 | 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 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 | """
Visualize canonical naming, side tags, and symmetry pairs across all datasets.
Produces:
1. Per-dataset skeleton with joints colored by side tag (L=red, R=blue, C=gray)
2. Canonical name labels on joints
3. Symmetry pairs connected by dashed lines
4. Cross-dataset canonical consistency heatmap
"""
import sys
import os
from pathlib import Path
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.patches as mpatches
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
from src.data.skeleton_graph import SkeletonGraph
from scripts.preprocess_bvh import forward_kinematics
RESULT_DIR = project_root / 'results' / 'canonical_check'
RESULT_DIR.mkdir(parents=True, exist_ok=True)
SIDE_COLORS = {'left': '#e74c3c', 'right': '#3498db', 'center': '#95a5a6'}
def plot_skeleton_canonical(ax, positions, parents, side_tags, canonical_names,
symmetry_pairs, title, label_fontsize=6):
"""Plot skeleton with side-colored joints and canonical name labels."""
J = len(parents)
pos = positions
# Draw bones
for j in range(J):
p = parents[j]
if p >= 0:
ax.plot3D([pos[j, 0], pos[p, 0]], [pos[j, 2], pos[p, 2]],
[pos[j, 1], pos[p, 1]], color='#bdc3c7', linewidth=1.5, zorder=1)
# Draw symmetry pairs as dashed lines
for i, j in symmetry_pairs:
if i < J and j < J:
mid_y = (pos[i, 1] + pos[j, 1]) / 2
ax.plot3D([pos[i, 0], pos[j, 0]], [pos[i, 2], pos[j, 2]],
[pos[i, 1], pos[j, 1]], color='#2ecc71', linewidth=0.8,
linestyle='--', alpha=0.5, zorder=2)
# Draw joints colored by side
for j in range(J):
color = SIDE_COLORS.get(side_tags[j], '#95a5a6')
ax.scatter3D([pos[j, 0]], [pos[j, 2]], [pos[j, 1]],
color=color, s=30, zorder=3, edgecolors='black', linewidths=0.3)
# Label joints with canonical names (subsample if too many)
step = max(1, J // 15)
for j in range(0, J, step):
ax.text(pos[j, 0], pos[j, 2], pos[j, 1] + 0.02,
canonical_names[j], fontsize=label_fontsize, ha='center', va='bottom',
color='black', alpha=0.8)
ax.set_title(title, fontsize=10, fontweight='bold')
ax.set_xlabel('X', fontsize=7)
ax.set_ylabel('Z', fontsize=7)
ax.set_zlabel('Y', fontsize=7)
ax.tick_params(labelsize=5)
# Equal axes
mid = pos.mean(axis=0)
span = max(pos.max(axis=0) - pos.min(axis=0)) / 2 + 0.05
ax.set_xlim(mid[0] - span, mid[0] + span)
ax.set_ylim(mid[2] - span, mid[2] + span)
ax.set_zlim(mid[1] - span, mid[1] + span)
def get_rest_pose(dataset_path, dataset_id):
"""Get rest pose joint positions from first motion."""
motions_dir = dataset_path / 'motions'
files = sorted(os.listdir(motions_dir))
if not files:
return None
d = dict(np.load(motions_dir / files[0], allow_pickle=True))
return d['joint_positions'][0] # first frame
def visualize_human_datasets():
"""Plot 1: All 6 human datasets side by side."""
fig = plt.figure(figsize=(24, 8))
datasets = ['humanml3d', 'lafan1', '100style', 'bandai_namco', 'cmu_mocap', 'mixamo']
for idx, ds in enumerate(datasets):
ds_path = project_root / 'data' / 'processed' / ds
s = dict(np.load(ds_path / 'skeleton.npz', allow_pickle=True))
sg = SkeletonGraph.from_dict(s)
canon = [str(n) for n in s['canonical_names']]
rest_pos = get_rest_pose(ds_path, ds)
if rest_pos is None:
continue
ax = fig.add_subplot(1, 6, idx + 1, projection='3d')
plot_skeleton_canonical(
ax, rest_pos, sg.parent_indices, sg.side_tags, canon,
sg.symmetry_pairs,
f'{ds}\n{sg.num_joints}j, {len(sg.symmetry_pairs)} sym pairs',
label_fontsize=5 if sg.num_joints > 30 else 6,
)
# Legend
patches = [
mpatches.Patch(color=SIDE_COLORS['left'], label='Left'),
mpatches.Patch(color=SIDE_COLORS['right'], label='Right'),
mpatches.Patch(color=SIDE_COLORS['center'], label='Center'),
mpatches.Patch(color='#2ecc71', label='Symmetry pair'),
]
fig.legend(handles=patches, loc='lower center', ncol=4, fontsize=9)
plt.suptitle('Human Datasets — Canonical Names + Side Tags + Symmetry',
fontsize=14, fontweight='bold')
plt.tight_layout(rect=[0, 0.05, 1, 0.95])
out = RESULT_DIR / 'human_canonical_overview.png'
plt.savefig(out, dpi=150, bbox_inches='tight')
plt.close()
print(f'Saved: {out}')
def visualize_zoo_animals():
"""Plot 2: Diverse Zoo animals with canonical names."""
species = ['Dog', 'Cat', 'Horse', 'Eagle', 'Trex', 'Spider',
'Ant', 'Anaconda', 'Dragon', 'Crab', 'Elephant', 'Bat']
fig = plt.figure(figsize=(24, 18))
zoo_path = project_root / 'data' / 'processed' / 'truebones_zoo'
motions_dir = zoo_path / 'motions'
# Find one motion per species
species_motions = {}
for f in sorted(os.listdir(motions_dir)):
d = dict(np.load(motions_dir / f, allow_pickle=True))
sp = str(d.get('species', ''))
if sp in species and sp not in species_motions:
species_motions[sp] = d
for idx, sp in enumerate(species):
if sp not in species_motions:
continue
d = species_motions[sp]
skel_path = zoo_path / 'skeletons' / f'{sp}.npz'
if not skel_path.exists():
continue
s = dict(np.load(skel_path, allow_pickle=True))
sg = SkeletonGraph.from_dict(s)
canon = [str(n) for n in s['canonical_names']]
rest_pos = d['joint_positions'][0]
ax = fig.add_subplot(3, 4, idx + 1, projection='3d')
plot_skeleton_canonical(
ax, rest_pos, sg.parent_indices, sg.side_tags, canon,
sg.symmetry_pairs,
f'{sp} ({sg.num_joints}j, {len(sg.symmetry_pairs)} sym)',
label_fontsize=5,
)
patches = [
mpatches.Patch(color=SIDE_COLORS['left'], label='Left'),
mpatches.Patch(color=SIDE_COLORS['right'], label='Right'),
mpatches.Patch(color=SIDE_COLORS['center'], label='Center'),
mpatches.Patch(color='#2ecc71', label='Symmetry pair'),
]
fig.legend(handles=patches, loc='lower center', ncol=4, fontsize=10)
plt.suptitle('Truebones Zoo — Canonical Names + Side Tags + Symmetry',
fontsize=14, fontweight='bold')
plt.tight_layout(rect=[0, 0.04, 1, 0.96])
out = RESULT_DIR / 'zoo_canonical_overview.png'
plt.savefig(out, dpi=150, bbox_inches='tight')
plt.close()
print(f'Saved: {out}')
def visualize_cross_dataset_consistency():
"""Plot 3: Heatmap showing canonical name consistency across datasets."""
# Collect canonical names for core body parts across datasets
core_parts = [
'pelvis', 'spine lower', 'spine mid', 'spine upper', 'neck', 'head',
'left collar', 'left upper arm', 'left forearm', 'left hand',
'right collar', 'right upper arm', 'right forearm', 'right hand',
'left upper leg', 'left lower leg', 'left foot', 'left toe',
'right upper leg', 'right lower leg', 'right foot', 'right toe',
]
datasets = ['humanml3d', 'lafan1', '100style', 'bandai_namco', 'cmu_mocap', 'mixamo']
matrix = np.zeros((len(core_parts), len(datasets)), dtype=np.float32)
for j, ds in enumerate(datasets):
s = dict(np.load(f'data/processed/{ds}/skeleton.npz', allow_pickle=True))
canon_set = set(str(n) for n in s['canonical_names'])
for i, part in enumerate(core_parts):
matrix[i, j] = 1.0 if part in canon_set else 0.0
fig, ax = plt.subplots(figsize=(10, 12))
im = ax.imshow(matrix, cmap='RdYlGn', aspect='auto', vmin=0, vmax=1)
ax.set_xticks(range(len(datasets)))
ax.set_xticklabels(datasets, rotation=45, ha='right', fontsize=9)
ax.set_yticks(range(len(core_parts)))
ax.set_yticklabels(core_parts, fontsize=9)
# Annotate cells
for i in range(len(core_parts)):
for j in range(len(datasets)):
text = '✓' if matrix[i, j] > 0.5 else '✗'
color = 'white' if matrix[i, j] > 0.5 else 'red'
ax.text(j, i, text, ha='center', va='center', fontsize=10, color=color)
ax.set_title('Cross-Dataset Canonical Name Coverage\n(22 core human body parts)',
fontsize=12, fontweight='bold')
plt.colorbar(im, ax=ax, label='Present in dataset', shrink=0.6)
plt.tight_layout()
out = RESULT_DIR / 'canonical_consistency_heatmap.png'
plt.savefig(out, dpi=150, bbox_inches='tight')
plt.close()
print(f'Saved: {out}')
def visualize_side_tag_stats():
"""Plot 4: Bar chart of side tag distribution per dataset."""
all_data = []
labels = []
datasets = ['humanml3d', 'lafan1', '100style', 'bandai_namco', 'cmu_mocap', 'mixamo']
for ds in datasets:
s = dict(np.load(f'data/processed/{ds}/skeleton.npz', allow_pickle=True))
sg = SkeletonGraph.from_dict(s)
n_l = sum(1 for t in sg.side_tags if t == 'left')
n_r = sum(1 for t in sg.side_tags if t == 'right')
n_c = sum(1 for t in sg.side_tags if t == 'center')
all_data.append((n_l, n_r, n_c, len(sg.symmetry_pairs)))
labels.append(f'{ds}\n({sg.num_joints}j)')
# Add Zoo species
for sp in ['Dog', 'Cat', 'Horse', 'Eagle', 'Trex', 'Spider', 'Anaconda', 'Dragon']:
s = dict(np.load(f'data/processed/truebones_zoo/skeletons/{sp}.npz', allow_pickle=True))
sg = SkeletonGraph.from_dict(s)
n_l = sum(1 for t in sg.side_tags if t == 'left')
n_r = sum(1 for t in sg.side_tags if t == 'right')
n_c = sum(1 for t in sg.side_tags if t == 'center')
all_data.append((n_l, n_r, n_c, len(sg.symmetry_pairs)))
labels.append(f'{sp}\n({sg.num_joints}j)')
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(16, 10))
x = range(len(labels))
lefts = [d[0] for d in all_data]
rights = [d[1] for d in all_data]
centers = [d[2] for d in all_data]
syms = [d[3] for d in all_data]
ax1.bar(x, lefts, color=SIDE_COLORS['left'], label='Left', alpha=0.8)
ax1.bar(x, rights, bottom=lefts, color=SIDE_COLORS['right'], label='Right', alpha=0.8)
ax1.bar(x, centers, bottom=[l+r for l,r in zip(lefts, rights)],
color=SIDE_COLORS['center'], label='Center', alpha=0.8)
ax1.set_xticks(x)
ax1.set_xticklabels(labels, fontsize=8)
ax1.set_ylabel('Joint Count')
ax1.set_title('Side Tag Distribution per Dataset/Species', fontweight='bold')
ax1.legend()
ax1.axvline(x=5.5, color='black', linestyle='--', alpha=0.3)
ax1.text(2.5, max(lefts)*2.5, 'Human', ha='center', fontsize=10, style='italic')
ax1.text(9.5, max(lefts)*2.5, 'Zoo Animals', ha='center', fontsize=10, style='italic')
ax2.bar(x, syms, color='#2ecc71', alpha=0.8)
ax2.set_xticks(x)
ax2.set_xticklabels(labels, fontsize=8)
ax2.set_ylabel('Symmetry Pairs')
ax2.set_title('Detected Symmetry Pairs per Dataset/Species', fontweight='bold')
ax2.axvline(x=5.5, color='black', linestyle='--', alpha=0.3)
plt.tight_layout()
out = RESULT_DIR / 'side_tag_stats.png'
plt.savefig(out, dpi=150, bbox_inches='tight')
plt.close()
print(f'Saved: {out}')
if __name__ == '__main__':
print('Generating canonical name visualizations...\n')
visualize_human_datasets()
visualize_zoo_animals()
visualize_cross_dataset_consistency()
visualize_side_tag_stats()
print(f'\nAll saved to: {RESULT_DIR}/')
|