import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from pathlib import Path
import re
def parse_trc(trc_path):
"""Parse a .trc file and return marker names, body knowledge, and metadata."""
with open(trc_path, 'r') as f:
traces = f.readlines()
meta_keys = traces[2].strip().cut up('t')
meta_vals = traces[3].strip().cut up('t')
metadata = dict(zip(meta_keys, meta_vals))
marker_line = traces[3].strip().cut up('t')
header_lines = 0
for i, line in enumerate(traces):
if line.strip() and never line.startswith(('PathFileType', 'DataRate',
'Body', 't')):
strive:
float(line.strip().cut up('t')[0])
header_lines = i
break
besides ValueError:
proceed
raw_markers = traces[3].strip().cut up('t')
markers = [m for m in raw_markers if m and m not in ('Frame#', 'Time')]
marker_names = []
for m in markers:
if m and (not marker_names or m != marker_names[-1]):
marker_names.append(m)
data_lines = traces[header_lines:]
knowledge = []
for line in data_lines:
vals = line.strip().cut up('t')
if len(vals) > 2:
strive:
row = [float(v) if v else np.nan for v in vals]
knowledge.append(row)
besides ValueError:
proceed
knowledge = np.array(knowledge)
return marker_names, knowledge, metadata
trc_files = sorted((work_dir / "pose-3d").glob("*.trc"))
print(f"📊 Discovered {len(trc_files)} TRC file(s):")
for f in trc_files:
print(f" {f.identify}")
trc_file = None
for f in trc_files:
if 'filt' in f.identify.decrease() and 'augm' not in f.identify.decrease():
trc_file = f
break
if trc_file is None and trc_files:
trc_file = trc_files[0]
if trc_file:
print(f"n📈 Visualizing: {trc_file.identify}")
marker_names, knowledge, metadata = parse_trc(trc_file)
print(f" Markers: {len(marker_names)}")
print(f" Frames: {knowledge.form[0]}")
print(f" Marker names: {marker_names[:10]}{'...' if len(marker_names) > 10 else ''}")
frames = knowledge[:, 0].astype(int) if knowledge.form[1] > 0 else []
instances = knowledge[:, 1] if knowledge.form[1] > 1 else []
coords = knowledge[:, 2:]
n_markers = len(marker_names)
mid_frame = len(knowledge) // 2
fig = plt.determine(figsize=(16, 6))
ax1 = fig.add_subplot(131, projection='3d')
xs = coords[mid_frame, 0::3][:n_markers]
ys = coords[mid_frame, 1::3][:n_markers]
zs = coords[mid_frame, 2::3][:n_markers]
ax1.scatter(xs, ys, zs, c="dodgerblue", s=40, alpha=0.8, edgecolors="navy")
for i, identify in enumerate(marker_names[:len(xs)]):
if i % 3 == 0:
ax1.textual content(xs[i], ys[i], zs[i], f' {identify}', fontsize=6, alpha=0.7)
ax1.set_xlabel('X (m)')
ax1.set_ylabel('Y (m)')
ax1.set_zlabel('Z (m)')
ax1.set_title(f'3D Keypoints (Body {int(frames[mid_frame])})', fontsize=10)
ax2 = fig.add_subplot(132)
key_markers = ['RAnkle', 'LAnkle', 'RWrist', 'LWrist', 'Nose']
colors_map = {'RAnkle': 'pink', 'LAnkle': 'blue', 'RWrist': 'orange',
'LWrist': 'inexperienced', 'Nostril': 'purple'}
for mkr in key_markers:
if mkr in marker_names:
idx = marker_names.index(mkr)
z_col = idx * 3 + 2
if z_col < coords.form[1]:
ax2.plot(instances, coords[:, z_col],
label=mkr, shade=colors_map.get(mkr, 'grey'),
linewidth=1.2, alpha=0.8)
ax2.set_xlabel('Time (s)')
ax2.set_ylabel('Z place (m)')
ax2.set_title('Vertical Trajectories', fontsize=10)
ax2.legend(fontsize=8, loc="finest")
ax2.grid(True, alpha=0.3)
ax3 = fig.add_subplot(133)
if len(instances) > 1:
dt = np.diff(instances)
dt[dt == 0] = 1e-6
for mkr in ['RAnkle', 'RWrist']:
if mkr in marker_names:
idx = marker_names.index(mkr)
x_col, y_col, z_col = idx * 3, idx * 3 + 1, idx * 3 + 2
if z_col < coords.form[1]:
dx = np.diff(coords[:, x_col])
dy = np.diff(coords[:, y_col])
dz = np.diff(coords[:, z_col])
pace = np.sqrt(dx**2 + dy**2 + dz**2) / dt
pace = np.clip(pace, 0, np.nanpercentile(pace, 99))
ax3.plot(instances[1:], pace, label=mkr,
shade=colors_map.get(mkr, 'grey'),
linewidth=0.8, alpha=0.7)
ax3.set_xlabel('Time (s)')
ax3.set_ylabel('Velocity (m/s)')
ax3.set_title('Marker Speeds (High quality Examine)', fontsize=10)
ax3.legend(fontsize=8)
ax3.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig(work_dir / 'trajectory_analysis.png', dpi=150, bbox_inches="tight")
plt.present()
print("✅ Trajectory plots saved to trajectory_analysis.png")
else:
print("⚠ No TRC file discovered to visualise.")
Elevate your perspective with NextTech Information, the place innovation meets perception.
Uncover the newest breakthroughs, get unique updates, and join with a worldwide community of future-focused thinkers.
Unlock tomorrow’s developments right this moment: learn extra, subscribe to our e-newsletter, and change into a part of the NextTech neighborhood at NextTech-news.com

