mp_hands = mp.solutions.hands
hands = mp_hands.Hands(
static_image_mode=False, # For video input
max_num_hands=2, # Maximum number of hands to detect
min_detection_confidence=0.5, # Minimum confidence for detection
min_tracking_confidence=0.5 # Minimum confidence for tracking
)
mp_drawing = mp.solutions.drawing_utils # For drawing hand landmarks
Open the input video
cap = cv2.VideoCapture('input_video.mp4')
Get video properties
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) # Video frame width
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) # Video frame height
fps = cap.get(cv2.CAP_PROP_FPS) # Original frames per second
Desired processing frame rate (2 frames per second)
desired_fps = 2
frame_skip = int(fps / desired_fps) # Calculate how many frames to skip
frame_count = 0 # To keep track of the frame number
Initialize Video Writer for output video
output_video = cv2.VideoWriter(
'output_video.mp4',
cv2.VideoWriter_fourcc(*'mp4v'),
desired_fps, # Set output video FPS to desired FPS
(width, height)
)
header = ['Frame', 'Hand']
for i in range(21): # 21 landmarks in MediaPipe Hands
header.extend([f'Landmark_{i}x', f'Landmark{i}y', f'Landmark{i}z'])
header.extend([f'Velocity{i}x', f'Velocity{i}y', f'Velocity{i}_z']) # Add velocity columns
Write header to CSV
csv_writer.writerow(header)
To store the landmarks from the previous frame
previous_landmarks = {}
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
code
Assistant
# Process every 'frame_skip' frames to achieve desired FPS
if frame_count % frame_skip == 0:
# Convert frame to RGB for MediaPipe processing
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
result = hands.process(frame_rgb)
# Create a copy of the frame for drawing
annotated_frame = frame.copy()
# Check if hand landmarks are detected
if result.multi_hand_landmarks:
for hand_index, hand_landmarks in enumerate(result.multi_hand_landmarks):
# Draw the hand landmarks on the frame
mp_drawing.draw_landmarks(
annotated_frame, hand_landmarks, mp_hands.HAND_CONNECTIONS)
# Get the wrist landmark as reference (landmark index 0)
wrist = hand_landmarks.landmark[mp_hands.HandLandmark.WRIST]
wrist_x = wrist.x
wrist_y = wrist.y
wrist_z = wrist.z
# Initialize a list to store adjusted landmarks and velocities
landmarks_row = [frame_count, hand_index]
# For velocity calculation: check if the current hand existed in the previous frame
if hand_index in previous_landmarks:
prev_landmarks = previous_landmarks[hand_index]
else:
# If no previous landmarks, initialize with zeros
prev_landmarks = [(0.0, 0.0, 0.0) for _ in range(21)]
for i, landmark in enumerate(hand_landmarks.landmark):
# Adjust landmarks relative to wrist
x = landmark.x - wrist_x
y = landmark.y - wrist_y
z = landmark.z - wrist_z
landmarks_row.extend([x, y, z])
# Calculate velocity: (current - previous) / time
prev_x, prev_y, prev_z = prev_landmarks[i]
velocity_x = (x - prev_x) / (1 / desired_fps) # Change in position / time interval
velocity_y = (y - prev_y) / (1 / desired_fps)
velocity_z = (z - prev_z) / (1 / desired_fps)
landmarks_row.extend([velocity_x, velocity_y, velocity_z])
# Write the landmarks and velocities to the CSV
csv_writer.writerow(landmarks_row)
# Update previous landmarks for the current hand
previous_landmarks[hand_index] = [(landmark.x - wrist_x, landmark.y - wrist_y, landmark.z - wrist_z) for landmark in hand_landmarks.landmark]
# Write the annotated frame to output video
output_video.write(annotated_frame)
frame_count += 1 # Increment frame count regardless of processing
cv2.imshow('Annotated Frame', annotated_frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
Release resources
cap.release()
output_video.release()
hands.close()
csv_file.close()
cv2.destroyAllWindows()
rewrite this code to add a kalman filter for landmark x,y,z, also explain, How can i add more features like angles or else, the video is created using hand held camera? which ml or dl algorithms would work best for activity recogniton on these landmarks?
Certainly! Below, you'll find a comprehensive guide to enhancing your existing hand landmark processing pipeline by integrating Kalman Filters for smoothing, adding additional features such as joint angles, and recommendations on machine learning/deep learning algorithms suitable for activity recognition based on these landmarks. This guide will help you handle data from a hand-held camera effectively.
1. Integrating Kalman Filters for Smoothing Landmarks
Why Use a Kalman Filter?
MediaPipe's hand landmark detection is robust but can still produce noisy data, especially with video from a hand-held camera. A Kalman Filter helps in predicting and smoothing the landmark positions by considering both the current measurements and the previous state, which leads to more stable and accurate tracking.
Implementation Overview:
Per-Landmark Filtering: Each landmark’s x, y, and z coordinates are independently filtered using separate Kalman Filters.
Initialization: For each hand (up to max_num_hands=2), initialize Kalman Filters for all 21 landmarks and their respective coordinates.
Updating Filters: At each processed frame, update the Kalman Filters with new measurements and retrieve the smoothed positions.
Modified Code with Kalman Filters:
python
import cv2
import mediapipe as mp
import csv
import numpy as np
# Function to initialize a 1D Kalman Filter for a single coordinate
def create_kalman_filter():
kf = cv2.KalmanFilter(2, 1) # 2 dynamic parameters, 1 measurement
kf.transitionMatrix = np.array([[1, 1],
[0, 1]], np.float32)
kf.measurementMatrix = np.array([[1, 0]], np.float32)
kf.processNoiseCov = np.array([[1, 0],
[0, 1]], np.float32) * 0.03
kf.measurementNoiseCov = np.array([[1]], np.float32) * 0.5
kf.errorCovPost = np.eye(2, dtype=np.float32)
return kf
# Initialize MediaPipe Hand Tracking
mp_hands = mp.solutions.hands
hands = mp_hands.Hands(
static_image_mode=False, # For video input
max_num_hands=2, # Maximum number of hands to detect
min_detection_confidence=0.5, # Minimum confidence for detection
min_tracking_confidence=0.5 # Minimum confidence for tracking
)
mp_drawing = mp.solutions.drawing_utils # For drawing hand landmarks
# Open the input video
cap = cv2.VideoCapture('input_video.mp4')
# Get video properties
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) # Video frame width
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) # Video frame height
fps = cap.get(cv2.CAP_PROP_FPS) # Original frames per second
# Desired processing frame rate (2 frames per second)
desired_fps = 2
frame_skip = max(int(fps / desired_fps), 1) # Ensure at least 1
frame_count = 0 # To keep track of the frame number
# Initialize Video Writer for output video
output_video = cv2.VideoWriter(
'output_video.mp4',
cv2.VideoWriter_fourcc(*'mp4v'),
desired_fps, # Set output video FPS to desired FPS
(width, height)
)
# Prepare to write to CSV file
csv_file = open('landmarks_with_velocity.csv', mode='w', newline='')
csv_writer = csv.writer(csv_file)
# Create CSV header
header = ['Frame', 'Hand']
for i in range(21): # 21 landmarks in MediaPipe Hands
header.extend([f'Landmark_{i}_x', f'Landmark_{i}_y', f'Landmark_{i}_z'])
header.extend([f'Velocity_{i}_x', f'Velocity_{i}_y', f'Velocity_{i}_z']) # Add velocity columns
# Write header to CSV
csv_writer.writerow(header)
# Initialize Kalman Filters for each hand and landmark
# Structure: kalman_filters[hand_index][landmark_index][coord] = KalmanFilter
kalman_filters = {}
for hand_idx in range(2): # Assuming max_num_hands=2
kalman_filters[hand_idx] = []
for lm_idx in range(21):
kf_x = create_kalman_filter()
kf_y = create_kalman_filter()
kf_z = create_kalman_filter()
kalman_filters[hand_idx].append({'x': kf_x, 'y': kf_y, 'z': kf_z})
# To store the landmarks from the previous frame for velocity calculation
previous_landmarks = {}
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
annotated_frame = frame.copy() # Initialize annotated_frame here to handle frames not processed
# Process every 'frame_skip' frames to achieve desired FPS
if frame_count % frame_skip == 0:
# Convert frame to RGB for MediaPipe processing
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
result = hands.process(frame_rgb)
# Check if hand landmarks are detected
if result.multi_hand_landmarks:
for hand_index, hand_landmarks in enumerate(result.multi_hand_landmarks):
if hand_index >= 2:
continue # Support up to 2 hands
# Draw the hand landmarks on the frame
mp_drawing.draw_landmarks(
annotated_frame, hand_landmarks, mp_hands.HAND_CONNECTIONS)
# Get the wrist landmark as reference (landmark index 0)
wrist = hand_landmarks.landmark[mp_hands.HandLandmark.WRIST]
wrist_x = wrist.x
wrist_y = wrist.y
wrist_z = wrist.z
# Initialize a list to store adjusted landmarks and velocities
landmarks_row = [frame_count, hand_index]
# For velocity calculation: check if the current hand existed in the previous frame
if hand_index in previous_landmarks:
prev_land = previous_landmarks[hand_index]
else:
# If no previous landmarks, initialize with zeros
prev_land = [(0.0, 0.0, 0.0) for _ in range(21)]
for lm_idx, landmark in enumerate(hand_landmarks.landmark):
# Adjust landmarks relative to wrist
measured_x = landmark.x - wrist_x
measured_y = landmark.y - wrist_y
measured_z = landmark.z - wrist_z
# Apply Kalman Filter to each coordinate
kf_x = kalman_filters[hand_index][lm_idx]['x']
kf_y = kalman_filters[hand_index][lm_idx]['y']
kf_z = kalman_filters[hand_index][lm_idx]['z']
# Update and predict based on measurements
kf_x.correct(np.array([[np.float32(measured_x)]]))
filtered_x = kf_x.predict()[0][0]
kf_y.correct(np.array([[np.float32(measured_y)]]))
filtered_y = kf_y.predict()[0][0]
kf_z.correct(np.array([[np.float32(measured_z)]]))
filtered_z = kf_z.predict()[0][0]
landmarks_row.extend([filtered_x, filtered_y, filtered_z])
# Calculate velocity: (current - previous) / time
prev_x, prev_y, prev_z = prev_land[lm_idx]
velocity_x = (filtered_x - prev_x) * desired_fps # Change per second
velocity_y = (filtered_y - prev_y) * desired_fps
velocity_z = (filtered_z - prev_z) * desired_fps
landmarks_row.extend([velocity_x, velocity_y, velocity_z])
# Write the landmarks and velocities to the CSV
csv_writer.writerow(landmarks_row)
# Update previous landmarks for the current hand
previous_landmarks[hand_index] = [
(kalman_filters[hand_index][i]['x'].statePost[0][0],
kalman_filters[hand_index][i]['y'].statePost[0][0],
kalman_filters[hand_index][i]['z'].statePost[0][0])
for i in range(21)
]
# Write the annotated frame to output video
output_video.write(annotated_frame)
# Display the frame (only the annotated frames are displayed)
if frame_count % frame_skip == 0 and ret:
cv2.imshow('Annotated Frame', annotated_frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
frame_count += 1 # Increment frame count regardless of processing
# Release resources
cap.release()
output_video.release()
hands.close()
csv_file.close()
cv2.destroyAllWindows()
Key Points in the Modified Code:
Kalman Filter Initialization: A helper function create_kalman_filter initializes a 1D Kalman Filter for each coordinate (x, y, z).
Kalman Filters Storage: The kalman_filters dictionary stores separate Kalman Filters for each landmark's x, y, and z coordinates, organized by hand_index and landmark_index.
Filtering Process:
For each detected landmark, the raw measured_x, measured_y, and measured_z are adjusted relative to the wrist.
Each coordinate is passed through its respective Kalman Filter (correct with measurement and predict to get the latest estimate).
The filtered positions are used to calculate velocities, providing smoother trajectory data.
Velocity Calculation: Velocities are calculated based on the change in filtered positions between frames, scaled by desired_fps to represent change per second.
2. Adding Additional Features (e.g., Joint Angles)
Incorporating extra features such as angles between joints can provide more insightful data for activity recognition. Here's how you can compute and include joint angles:
Understanding Joint Angles:
Joint angles describe the relative orientation between connected landmarks. For example, the angle at the elbow can be determined by the positions of the shoulder, elbow, and wrist landmarks.
Implementing Angle Calculations:
Select Joints for Angles: Determine which joint angles are relevant for your activity recognition task. Common choices include:
Thumb, index, middle, ring, and pinky finger angles.
Palm orientation angles.
Finger curl or spread.
Compute Angles:
Vector Approach: Compute vectors between three consecutive landmarks and calculate the angle between them.
Dot Product Formula: Use the dot product to find the angle between two vectors.
Store Angles: Extend the CSV header and data rows to include these computed angles.
Example: Calculating Finger Joint Angles
Below is an example of how to compute angles at the knuckles (proximal interphalangeal joints) of each finger.
python
import math
def calculate_angle(a, b, c):
"""
Calculate the angle at point b given three points a, b, c.
Points are tuples/lists of (x, y, z).
Returns angle in degrees.
"""
ba = np.array(a) - np.array(b)
bc = np.array(c) - np.array(b)
# Calculate the cosine of the angle using dot product
cosine_angle = np.dot(ba, bc) / (np.linalg.norm(ba) * np.linalg.norm(bc))
# Clamp the cosine to the valid range to avoid numerical issues
cosine_angle = np.clip(cosine_angle, -1.0, 1.0)
angle = np.degrees(np.arccos(cosine_angle))
return angle
Updating the CSV Header:
python
# After existing header definitions
angle_headers = []
# Example: Calculate angles for each finger's PIP joint
for finger in ['Thumb', 'Index', 'Middle', 'Ring', 'Pinky']:
angle_headers.append(f'{finger}_PIP_Angle')
header.extend(angle_headers)
csv_writer.writerow(header)
Calculating and Adding Angles to Each Row:
python
# Inside the hand processing loop, after landmark velocities
# Define landmark indices for each finger's PIP joints
finger_pip_indices = {
'Thumb': (mp_hands.HandLandmark.THUMB_CMC,
mp_hands.HandLandmark.THUMB_MCP,
mp_hands.HandLandmark.THUMB_IP),
'Index': (mp_hands.HandLandmark.INDEX_FINGER_MCP,
mp_hands.HandLandmark.INDEX_FINGER_PIP,
mp_hands.HandLandmark.INDEX_FINGER_DIP),
'Middle': (mp_hands.HandLandmark.MIDDLE_FINGER_MCP,
mp_hands.HandLandmark.MIDDLE_FINGER_PIP,
mp_hands.HandLandmark.MIDDLE_FINGER_DIP),
'Ring': (mp_hands.HandLandmark.RING_FINGER_MCP,
mp_hands.HandLandmark.RING_FINGER_PIP,
mp_hands.HandLandmark.RING_FINGER_DIP),
'Pinky': (mp_hands.HandLandmark.PINKY_MCP,
mp_hands.HandLandmark.PINKY_PIP,
mp_hands.HandLandmark.PINKY_DIP)
}
angles = []
for finger, (a_idx, b_idx, c_idx) in finger_pip_indices.items():
a = [
kalman_filters[hand_index][a_idx.value]['x'].statePost[0][0],
kalman_filters[hand_index][a_idx.value]['y'].statePost[0][0],
kalman_filters[hand_index][a_idx.value]['z'].statePost[0][0]
]
b = [
kalman_filters[hand_index][b_idx.value]['x'].statePost[0][0],
kalman_filters[hand_index][b_idx.value]['y'].statePost[0][0],
kalman_filters[hand_index][b_idx.value]['z'].statePost[0][0]
]
c = [
kalman_filters[hand_index][c_idx.value]['x'].statePost[0][0],
kalman_filters[hand_index][c_idx.value]['y'].statePost[0][0],
kalman_filters[hand_index][c_idx.value]['z'].statePost[0][0]
]
angle = calculate_angle(a, b, c)
angles.append(angle)
landmarks_row.extend(angles) # Add angles to the CSV row
Notes:
Choice of Joints: Select joints that are most informative for your specific activity recognition task.
Handling Missing Data: Ensure that all required landmarks are detected before calculating angles to avoid errors.
Normalization: Depending on your use case, you might need to normalize angles or other features.
3. Recommendations for Machine Learning/Deep Learning Algorithms for Activity Recognition
Considerations:
Data Characteristics:
Temporal Dynamics: Activities unfold over time, so temporal dependencies are crucial.
Noise and Variability: Hand-held camera data can introduce jitter and varying viewpoints.
Feature Representation:
Sequences of Landmarks: Time-series data where each frame contains 63 landmark coordinates (21 landmarks × 3 coordinates).
Additional Features: Joint angles, distances between key landmarks, velocities.
Suitable Algorithms:
Recurrent Neural Networks (RNNs):
LSTM (Long Short-Term Memory): Effective for capturing long-term dependencies in sequential data.
GRU (Gated Recurrent Unit): Similar to LSTM but with a different gating mechanism, often faster to train.
Temporal Convolutional Networks (TCNs):
Utilize convolutional layers with temporal receptive fields to capture temporal patterns.
Often outperform RNNs in tasks requiring long-range dependencies.
Transformer-Based Models:
Temporal Transformers: Models like the Transformer can handle sequences with attention mechanisms, capturing global dependencies efficiently.
Pros: Highly parallelizable and effective for long sequences.
Graph Neural Networks (GNNs):
Spatial-Temporal GNNs: Model the hand as a graph with edges representing the connections between landmarks.
Pros: Naturally handle the intrinsic structure of hand landmarks and their relationships.
Hybrid Models:
Combine CNNs or GNNs for spatial feature extraction with RNNs or Transformers for temporal modeling.
Traditional Machine Learning Models:
Support Vector Machines (SVM), Random Forests, Gradient Boosting: Suitable for smaller datasets or as baselines.
Feature Engineering Required: Less effective with raw sequential data; better with well-engineered features.
Recommendation:
Given the nature of your data (sequential landmark positions with potential noise from a hand-held camera), LSTM-based models are a solid starting point due to their ability to capture temporal dependencies. If computational resources permit, exploring Transformer-based models or Graph Neural Networks can provide advanced performance, especially if you incorporate additional spatial relationships via joint angles or distances.
Implementation Tips:
Data Preprocessing:
Normalization: Scale landmark coordinates and angles to a consistent range.
Handling Missing Data: Impute or filter out frames with missing or unreliable landmarks.
Segmentation: Divide the data into meaningful sequences/windows representing individual activities.
Data Augmentation:
Synthetic Variations: Introduce slight perturbations to simulate different viewpoints or noise conditions.
Temporal Shifts: Slightly shift sequences in time to increase dataset variability.
Model Training:
Train-Test Split: Ensure temporal continuity to prevent data leakage (e.g., split based on time rather than randomly).
Regularization: Use techniques like dropout to prevent overfitting, especially with complex models.
Evaluation Metrics: Choose metrics suitable for classification tasks, such as accuracy, F1-score, precision, and recall.
4. Handling Data from a Hand-Held Camera
Data captured from a hand-held camera presents unique challenges:
Camera Motion: Unintended movements can introduce additional noise and variability.
Viewpoint Variations: Changes in camera angle can affect landmark positions relative to the camera.
Occlusions: Hands may move in and out of the frame or occlude parts of each other.
Strategies to Mitigate Challenges:
Stabilization:
Apply video stabilization techniques to reduce camera-induced jitter.
Coordinate Normalization:
Normalize landmark positions relative to a fixed point (e.g., the wrist) to make features invariant to camera movements.
Robust Feature Extraction:
Incorporate features that are less sensitive to viewpoint changes, such as angles and distances rather than absolute positions.
Augmented Data:
Simulate camera movements and variations during training to make the model more robust.
Multi-View Training:
If possible, collect data from multiple camera angles to enhance model generalization.
Conclusion
By integrating Kalman Filters, you can significantly enhance the quality of your landmark data, making it more reliable for downstream tasks like activity recognition. Adding additional features such as joint angles can provide deeper insights into hand movements, further enriching the dataset. When it comes to selecting machine learning or deep learning models, it's essential to consider the temporal nature of the data and the challenges posed by hand-held camera recordings. Starting with LSTM-based models is advisable, with potential exploration into more advanced architectures like Transformers or Graph Neural Networks based on performance and resource availability.
Feel free to reach out if you have further questions or need assistance with specific parts of the implementation!