AI for Rehabilitation and Motion Analysis
Module: Healthcare AI | Difficulty: Advanced
Joint Angle Calculation
Gait Cycle Phase
Rehabilitation Metrics
| Metric | Formula | Clinical Use |
|---|---|---|
| Range of Motion | Joint assessment | |
| Gait Symmetry | Walking analysis | |
| Balance Score | Balance assessment | |
| Movement Smoothness | Motor control |
import torch
import torch.nn as nn
import numpy as np
class PoseEstimator(nn.Module):
def __init__(self, num_keypoints=17):
super().__init__()
self.backbone = models.resnet50(pretrained=True)
num_features = self.backbone.fc.in_features
self.backbone.fc = nn.Identity()
self.keypoint_head = nn.Sequential(
nn.Linear(num_features, 512), nn.ReLU(),
nn.Linear(512, num_keypoints * 2))
self.confidence_head = nn.Sequential(
nn.Linear(num_features, 512), nn.ReLU(),
nn.Linear(512, num_keypoints))
def forward(self, x):
features = self.backbone(x)
keypoints = self.keypoint_head(features).reshape(-1, 17, 2)
confidence = torch.sigmoid(self.confidence_head(features))
return keypoints, confidence
class GaitAnalyzer(nn.Module):
def __init__(self):
super().__init__()
self.temporal_encoder = nn.LSTM(34, 64, batch_first=True, bidirectional=True)
self.spatial_encoder = nn.Sequential(
nn.Linear(34, 64), nn.ReLU(), nn.Linear(64, 64))
self.gait_classifier = nn.Linear(128, 5)
def forward(self, keypoint_sequence):
temporal_out, _ = self.temporal_encoder(keypoint_sequence)
spatial_out = self.spatial_encoder(keypoint_sequence[:, -1, :])
combined = torch.cat([temporal_out[:, -1, :], spatial_out], dim=1)
return self.gait_classifier(combined)
def compute_joint_angle(point_a, point_b, point_c):
ba = point_a - point_b
bc = point_c - point_b
cosine_angle = np.dot(ba, bc) / (np.linalg.norm(ba) * np.linalg.norm(bc) + 1e-6)
return np.degrees(np.arccos(np.clip(cosine_angle, -1.0, 1.0)))
def compute_rom(angles):
return np.max(angles) - np.min(angles)
pose_model = PoseEstimator()
x = torch.randn(1, 3, 224, 224)
keypoints, confidence = pose_model(x)
print(f'Keypoints shape: {keypoints.shape}, Confidence: {confidence.shape}')
gait_model = GaitAnalyzer()
sequence = torch.randn(1, 30, 34)
gait_class = gait_model(sequence)
print(f'Gait classification: {gait_class.shape}')
angle = compute_joint_angle(
np.array([0, 0, 0]), np.array([0, 1, 0]), np.array([1, 1, 0]))
print(f'Joint angle: {angle:.1f} degrees')
Research Insight: AI-based rehabilitation monitoring enables remote patient assessment and telerehabilitation. Pose estimation models can track patient movements during home exercises and provide real-time feedback. Self-supervised pre-training on large-scale human pose datasets significantly improves robustness to real-world variations in lighting and camera angles.