AI Skill Report Card
Medical Motion Detection Registration
YAML--- name: medical-motion-detection-registration description: Builds simple, explainable 2D motion detection pipelines for medical radiation safety using fixed-reference image registration, displacement fields, warped residuals, ROI/head masks, and temporal stage logic. Use when developing deformation-based motion detection systems for segmentation control and radiation stop/recovery decisions. ---
Medical Motion Detection Registration
Quick Start15 / 15
Pythonimport cv2 import numpy as np from scipy.ndimage import gaussian_filter # Basic motion detection pipeline def detect_motion(reference_img, current_img, roi_mask=None): # Register current to reference displacement_field = register_images(reference_img, current_img) # Warp current image to reference space warped_img = apply_displacement(current_img, displacement_field) # Calculate residual residual = np.abs(reference_img - warped_img) # Apply ROI mask if provided if roi_mask is not None: residual = residual * roi_mask # Motion metric motion_score = np.mean(residual) return motion_score, displacement_field, warped_img, residual
Recommendation▾
Add specific input/output examples with actual image arrays and displacement values in the examples section
Workflow15 / 15
Stage 1: Reference Establishment
- Acquire baseline reference image
- Generate head/body ROI mask
- Validate image quality (contrast, artifacts)
- Store reference for registration pipeline
Stage 2: Real-time Registration
- Capture current frame
- Register to fixed reference using optical flow or feature matching
- Calculate dense displacement field
- Warp current image to reference space
Stage 3: Motion Analysis
- Compute warped residual (reference - warped_current)
- Apply ROI mask to focus on anatomy of interest
- Calculate motion metrics (mean, max, percentile)
- Apply temporal filtering (moving average, outlier rejection)
Stage 4: Decision Logic
- Compare motion score to threshold
- Implement hysteresis (different thresholds for stop/resume)
- Log motion events with timestamps
- Trigger radiation control signals
Recommendation▾
Include a complete minimal working example that can be copy-pasted and run immediately
Core Functions
Image Registration:
Pythondef register_images(reference, current): # Lucas-Kanade optical flow for dense registration flow = cv2.calcOpticalFlowPyrLK( reference.astype(np.uint8), current.astype(np.uint8), corners, None, **lk_params ) # Convert sparse flow to dense displacement field displacement_field = interpolate_flow(flow, reference.shape) return displacement_field def apply_displacement(image, displacement_field): h, w = image.shape map_x = np.arange(w) + displacement_field[:, :, 0] map_y = np.arange(h) + displacement_field[:, :, 1] warped = cv2.remap(image, map_x, map_y, cv2.INTER_LINEAR) return warped
ROI Mask Generation:
Pythondef create_head_mask(image, method='threshold'): if method == 'threshold': # Simple intensity thresholding mask = image > np.percentile(image, 20) elif method == 'contour': # Find largest contour (assumes head is largest object) contours, _ = cv2.findContours( (image > threshold).astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE ) largest_contour = max(contours, key=cv2.contourArea) mask = cv2.fillPoly(np.zeros_like(image), [largest_contour], 1) # Morphological cleanup kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)) mask = cv2.morphologyEx(mask.astype(np.uint8), cv2.MORPH_CLOSE, kernel) return mask.astype(bool)
Temporal Stage Logic:
Pythonclass MotionDetector: def __init__(self, motion_threshold=5.0, hysteresis_factor=0.8): self.threshold = motion_threshold self.resume_threshold = motion_threshold * hysteresis_factor self.motion_history = [] self.is_stopped = False def update(self, motion_score): self.motion_history.append(motion_score) if len(self.motion_history) > 10: # Keep last 10 frames self.motion_history.pop(0) # Temporal smoothing smoothed_score = np.median(self.motion_history[-3:]) # 3-frame median # State machine logic if not self.is_stopped and smoothed_score > self.threshold: self.is_stopped = True return "STOP_RADIATION" elif self.is_stopped and smoothed_score < self.resume_threshold: self.is_stopped = False return "RESUME_RADIATION" return "CONTINUE"
Examples17 / 20
Example 1: Basic Setup Input: 512x512 grayscale image, 2mm motion threshold Output:
Motion score: 1.23mm (CONTINUE)
Displacement field: 512x512x2 array
Max displacement: 0.8mm at (234, 156)
Example 2: Motion Event Input: Patient movement during scan Output:
Motion score: 5.67mm (STOP_RADIATION)
Event logged: 14:23:15.234
Recovery time: 2.1 seconds
Example 3: ROI Masking Input: Full-body image with 40% background Output: Head-only ROI reduces false positives by 75%
Recommendation▾
Reduce some technical explanations that assume less domain knowledge than Claude likely has
Best Practices
Registration Quality:
- Use pyramid-based registration for large motions
- Validate registration with inverse consistency check
- Handle registration failures gracefully (flag bad frames)
Threshold Setting:
- Start with 2-3mm for cranial applications
- Use different thresholds for different anatomical regions
- Implement adaptive thresholds based on image quality
Temporal Filtering:
- Use median filter (3-5 frames) to reject outliers
- Implement exponential moving average for trend detection
- Apply different time constants for motion onset vs. recovery
Safety Margins:
- Always err on the side of radiation safety
- Implement watchdog timer for system failures
- Log all motion events for quality assurance
Common Pitfalls
Registration Artifacts:
- Don't use registration on low-contrast regions
- Avoid over-smoothing that masks real motion
- Check for registration convergence failures
False Positives:
- Breathing motion can trigger false alarms - use respiratory gating
- Image noise changes between frames - apply consistent preprocessing
- Intensity variations from beam hardening - normalize images
Timing Issues:
- Don't use overly aggressive temporal filtering - delays detection
- Avoid hysteresis bands that are too narrow - causes oscillation
- System latency must be accounted for in safety margins
Mask Problems:
- Static masks don't account for patient positioning changes
- Over-restrictive ROIs can miss important motion
- Under-inclusive masks allow background noise to dominate