Close Menu
    Facebook X (Twitter) Instagram
    Articles Stock
    • Home
    • Technology
    • AI
    • Pages
      • About us
      • Contact us
      • Disclaimer For Articles Stock
      • Privacy Policy
      • Terms and Conditions
    Facebook X (Twitter) Instagram
    Articles Stock
    AI

    A Coding Information to Markerless 3D Human Kinematics with Pose2Sim, RTMPose, and OpenSim

    Naveed AhmadBy Naveed Ahmad11/04/2026Updated:11/04/2026No Comments3 Mins Read
    blog 1 6


    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 information, and metadata."""
       with open(trc_path, 'r') as f:
           traces = f.readlines()
    
    
       meta_keys = traces[2].strip().break up('t')
       meta_vals = traces[3].strip().break up('t')
       metadata = dict(zip(meta_keys, meta_vals))
    
    
       marker_line = traces[3].strip().break 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().break up('t')[0])
                   header_lines = i
                   break
               besides ValueError:
                   proceed
    
    
       raw_markers = traces[3].strip().break 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:]
       information = []
       for line in data_lines:
           vals = line.strip().break up('t')
           if len(vals) > 2:
               strive:
                   row = [float(v) if v else np.nan for v in vals]
                   information.append(row)
               besides ValueError:
                   proceed
    
    
       information = np.array(information)
       return marker_names, information, 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.title}")
    
    
    trc_file = None
    for f in trc_files:
       if 'filt' in f.title.decrease() and 'augm' not in f.title.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.title}")
       marker_names, information, metadata = parse_trc(trc_file)
       print(f"   Markers: {len(marker_names)}")
       print(f"   Frames:  {information.form[0]}")
       print(f"   Marker names: {marker_names[:10]}{'...' if len(marker_names) > 10 else ''}")
    
    
       frames = information[:, 0].astype(int) if information.form[1] > 0 else []
       occasions = information[:, 1] if information.form[1] > 1 else []
       coords = information[:, 2:]
    
    
       n_markers = len(marker_names)
    
    
       mid_frame = len(information) // 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, title in enumerate(marker_names[:len(xs)]):
           if i % 3 == 0:
               ax1.textual content(xs[i], ys[i], zs[i], f' {title}', 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': 'crimson', '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(occasions, 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(occasions) > 1:
           dt = np.diff(occasions)
           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])
                       velocity = np.sqrt(dx**2 + dy**2 + dz**2) / dt
                       velocity = np.clip(velocity, 0, np.nanpercentile(velocity, 99))
                       ax3.plot(occasions[1:], velocity, 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 Test)', 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.")



    Source link

    Naveed Ahmad

    Related Posts

    The right way to watch NASA’s Artemis II splash again right down to Earth

    11/04/2026

    Suspect Arrested for Allegedly Throwing Molotov Cocktail at Sam Altman’s Residence

    11/04/2026

    Battery recycler Ascend Components recordsdata for chapter

    11/04/2026
    Leave A Reply Cancel Reply

    Categories
    • AI
    Recent Comments
      Facebook X (Twitter) Instagram Pinterest
      © 2026 ThemeSphere. Designed by ThemeSphere.

      Type above and press Enter to search. Press Esc to cancel.