Certainly! Below is the rewritten code with irrelevant lines removed, along with a detailed explanation. I'll also address how to modify the code to detect hands with black gloves, suggest performance enhancements, and discuss other applications of the Kalman filter in hand activity recognition.
Cleaned-Up Code:
import cv2
import mediapipe as mp
import csv
import numpy as np
# Define a 1D Kalman Filter class with velocity
class KalmanFilter1D:
def __init__(self, initial_position=0.0, initial_velocity=0.0):
# State vector [position, velocity]
self.state = np.array([[initial_position],
[initial_velocity]], dtype=np.float32)
# State covariance matrix
self.covariance = np.eye(2, dtype=np.float32)
# State transition matrix (assuming constant velocity)
self.F = np.array([[1, 1],
[0, 1]], dtype=np.float32)
# Measurement matrix (we only measure position)
self.H = np.array([[1, 0]], dtype=np.float32)
# Process noise covariance
self.Q = np.array([[1e-4, 0],
[0, 1e-4]], dtype=np.float32)
# Measurement noise covariance
self.R = np.array([[1e-1]], dtype=np.float32)
# Kalman gain
self.K = np.zeros((2, 1), dtype=np.float32)
# Initialization flag
self.initialized = False
def initialize(self, measurement):
self.state = np.array([[measurement],
[0.0]], dtype=np.float32)
self.initialized = True
def predict(self):
# Predict the next state
self.state = self.F @ self.state
# Update the state covariance matrix
self.covariance = self.F @ self.covariance @ self.F.T + self.Q
def update(self, measurement):
if not self.initialized:
self.initialize(measurement)
return self.state[0][0], self.state[1][0] # Position, Velocity
# Measurement residual
y = np.array([[measurement]]) - (self.H @ self.state)
# Measurement covariance
S = self.H @ self.covariance @ self.H.T + self.R
# Kalman gain
self.K = self.covariance @ self.H.T @ np.linalg.inv(S)
# Update the state estimate
self.state = self.state + self.K @ y
# Update the covariance estimate
I = np.eye(self.F.shape[0], dtype=np.float32)
self.covariance = (I - self.K @ self.H) @ self.covariance
return self.state[0][0], self.state[1][0] # Position, Velocity
# 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
desired_fps = 10
frame_skip = max(int(fps / desired_fps), 1) # Ensure at least 1
frame_count = 0 # To keep track of the frame number
# Time difference between frames
delta_t = 1 / desired_fps
# Initialize Video Writer for output video
output_video = cv2.VideoWriter(
'output_video_kf.mp4',
cv2.VideoWriter_fourcc(*'mp4v'),
desired_fps, # Set output video FPS to desired FPS
(width, height)
)
# Prepare to write to CSV file
with open('landmarks_with_velocity_and_kalman.csv', mode='w', newline='') as csv_file:
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',
f'Landmark_{i}_velocity_x', f'Landmark_{i}_velocity_y', f'Landmark_{i}_velocity_z',
f'Landmark_{i}_kalman_x', f'Landmark_{i}_kalman_y', f'Landmark_{i}_kalman_z'
])
# Write header to CSV
csv_writer.writerow(header)
# Initialize Kalman filters for all 21 landmarks (for each hand)
kalman_filters = {
'Left': [{'x': KalmanFilter1D(), 'y': KalmanFilter1D(), 'z': KalmanFilter1D()} for _ in range(21)],
'Right': [{'x': KalmanFilter1D(), 'y': KalmanFilter1D(), 'z': KalmanFilter1D()} for _ in range(21)]
}
# Store previous landmarks to compute velocity
previous_landmarks = {'Left': None, 'Right': None}
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
# 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 and result.multi_handedness:
for hand_landmarks, handedness in zip(result.multi_hand_landmarks, result.multi_handedness):
# Get hand label ('Left' or 'Right')
hand_label = handedness.classification[0].label
# 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
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
landmarks_row = [frame_count, hand_label]
current_landmarks = [] # To store current frame's landmarks
current_velocities = [] # To store current frame's velocities
for i, landmark in enumerate(hand_landmarks.landmark):
# Original normalized coordinates
x_raw = landmark.x
y_raw = landmark.y
z_raw = landmark.z
# Adjust landmarks relative to wrist
x = x_raw - wrist_x
y = y_raw - wrist_y
z = z_raw - wrist_z
# Calculate velocity using previous landmarks
if previous_landmarks[hand_label] is not None:
previous_x, previous_y, previous_z = previous_landmarks[hand_label][i]
velocity_x = (x - previous_x) / delta_t
velocity_y = (y - previous_y) / delta_t
velocity_z = (z - previous_z) / delta_t
else:
velocity_x = 0.0
velocity_y = 0.0
velocity_z = 0.0
current_landmarks.append((x, y, z))
current_velocities.append((velocity_x, velocity_y, velocity_z))
# Apply Kalman filter to the x, y, and z coordinates
kalman_x = kalman_filters[hand_label][i]['x']
kalman_y = kalman_filters[hand_label][i]['y']
kalman_z = kalman_filters[hand_label][i]['z']
# Prediction step
kalman_x.predict()
kalman_y.predict()
kalman_z.predict()
# Update step with measurement
kalman_x_estimated, kalman_velocity_x = kalman_x.update(x)
kalman_y_estimated, kalman_velocity_y = kalman_y.update(y)
kalman_z_estimated, kalman_velocity_z = kalman_z.update(z)
# Visualization of Raw and Kalman-Filtered Landmarks
# Convert normalized coordinates to pixel coordinates for visualization
raw_x_pixel = int(x_raw * width)
raw_y_pixel = int(y_raw * height)
kalman_x_abs = kalman_x_estimated + wrist_x
kalman_y_abs = kalman_y_estimated + wrist_y
kalman_x_pixel = int(kalman_x_abs * width)
kalman_y_pixel = int(kalman_y_abs * height)
# Ensure pixel values are within image bounds
raw_x_pixel = np.clip(raw_x_pixel, 0, width - 1)
raw_y_pixel = np.clip(raw_y_pixel, 0, height - 1)
kalman_x_pixel = np.clip(kalman_x_pixel, 0, width - 1)
kalman_y_pixel = np.clip(kalman_y_pixel, 0, height - 1)
# Draw raw landmark (green)
cv2.circle(annotated_frame, (raw_x_pixel, raw_y_pixel), 3, (0, 255, 0), -1)
# Draw Kalman-filtered landmark (red)
cv2.circle(annotated_frame, (kalman_x_pixel, kalman_y_pixel), 3, (0, 0, 255), -1)
# Append data to CSV row
landmarks_row.extend([
x, y, z,
velocity_x, velocity_y, velocity_z,
kalman_x_estimated, kalman_y_estimated, kalman_z_estimated
])
# Write the landmarks to CSV
csv_writer.writerow(landmarks_row)
# Update previous landmarks
previous_landmarks[hand_label] = current_landmarks
# Write the annotated frame to output video
output_video.write(annotated_frame)
frame_count += 1 # Increment frame count regardless of processing
# Release resources
cap.release()
output_video.release()
hands.close()
Detailed Explanation:
1. Imports and Class Definition
-
Libraries Imported:
cv2: OpenCV library for video processing.
mediapipe: Google's MediaPipe for hand tracking.
csv: For writing data to CSV files.
numpy: For numerical computations.
-
KalmanFilter1D Class:
- A custom 1D Kalman Filter that tracks position and velocity.
- State Vector (
self.state): Contains position and velocity.
- State Covariance (
self.covariance): Uncertainty of the state.
- State Transition Matrix (
self.F): Models state evolution.
- Measurement Matrix (
self.H): Relates the measurement to the state.
- Process Noise Covariance (
self.Q): Models process noise.
- Measurement Noise Covariance (
self.R): Models measurement noise.
- Methods:
initialize(): Initializes the state with the first measurement.
predict(): Predicts the next state and covariance.
update(): Updates the state with a new measurement.
2. MediaPipe Hand Tracking Initialization
mp_hands.Hands(): Initializes the hand tracking model with parameters for video processing.
static_image_mode=False: Indicates video input.
max_num_hands=2: Detect up to two hands.
min_detection_confidence=0.5: Minimum confidence for detecting hands.
min_tracking_confidence=0.5: Minimum confidence for tracking hands.
3. Video Processing Setup
-
Video Capture:
- Open the input video file using
cv2.VideoCapture('input_video.mp4').
- Retrieve video properties such as width, height, and frames per second (FPS).
-
Desired Frame Rate:
- Set a
desired_fps to control processing speed.
- Calculate
frame_skip to process every nth frame to achieve the desired FPS.
-
Output Video Writer:
- Initialize
cv2.VideoWriter() to save the annotated frames into an output video.
4. CSV File Preparation
- CSV Header:
- Create a header row for the CSV file, including frame number, hand label, coordinates, velocities, and Kalman-filtered positions for each of the 21 hand landmarks.
5. Kalman Filters Initialization
- Kalman Filters Structure:
- A dictionary
kalman_filters storing KalmanFilter1D instances for each landmark and each coordinate (x, y, z) for both left and right hands.
6. Main Processing Loop
-
Frame Processing:
- Read frames from the video in a loop.
- Process frames at intervals determined by
frame_skip.
-
Hand Detection:
- Convert the frame to RGB and process it with
hands.process() to detect hand landmarks.
-
Landmarks Processing:
- For each detected hand:
- Hand Label: Determine if the hand is left or right.
- Landmarks Adjustment:
- Use the wrist landmark as a reference point.
- Adjust other landmarks to be relative to the wrist position.
- Velocity Calculation:
- Compute velocities for each landmark using the difference from the previous frame.
- Kalman Filtering:
- Predict the next state for each coordinate (x, y, z).
- Update the state with the current measurement.
- Visualization:
- Draw raw and Kalman-filtered landmarks on the frame for comparison.
- CSV Writing:
- Append the computed data to the CSV file.
7. Resource Cleanup
- After processing, release the video capture, close the output video writer, and close the MediaPipe resources.
Detecting Hands with Black Gloves:
MediaPipe's hand detection relies on machine learning models trained on vast datasets of hand images. Detecting hands wearing black gloves can be challenging because:
- Contrast Issues: Black gloves against a dark background may not provide enough contrast.
- Texture and Features: Gloves obscure skin features like knuckles and lines, which can be cues for detection.
Possible Solutions:
-
Adjust Detection Confidence Thresholds:
- Lower the
min_detection_confidence and min_tracking_confidence to make the detector more sensitive.
hands = mp_hands.Hands(
static_image_mode=False,
max_num_hands=2,
min_detection_confidence=0.3, # Lowered from 0.5
min_tracking_confidence=0.3 # Lowered from 0.5
)
-
Enhance Image Preprocessing:
- Improve contrast using image processing techniques.
- Convert the image to different color spaces, such as HSV, and enhance specific channels.
-
Use a Custom Model:
- Train a custom hand detection model that includes images of hands wearing black gloves.
- Utilize transfer learning with datasets that include gloved hands.
-
Background Control:
- Ensure a high-contrast background against the black gloves.
- Use a lighter background to make the gloves stand out.
-
Infrared Imaging:
- Use cameras that capture infrared light, as gloves may not block IR radiation emitted from the hand.
-
Apply Alternative Detection Methods:
- Use contour detection or motion detection to identify hands based on shape and movement.
Enhancing Performance:
-
Optimize Frame Processing:
-
Increase frame_skip:
- Skip more frames to process fewer frames per second.
-
Use Multi-threading or Multiprocessing:
- Parallelize the processing of frames.
-
Leverage GPU Acceleration:
- Use frameworks that support GPU acceleration for faster computations.
-
Optimize Kalman Filter Parameters:
- Adjust
self.Q and self.R in the KalmanFilter1D class to better reflect the noise characteristics.
-
Avoid Unnecessary Computations:
-
Efficient Data Structures:
- Use NumPy arrays efficiently and avoid unnecessary data copying.
-
Conditional Logging:
- If writing to CSV is slowing down processing, consider buffering writes or reducing the amount of logged data.
Other Applications of Kalman Filter in Hand Activity Recognition:
-
Smoothing Noisy Data:
- Reduce jitter in hand landmark positions for smoother gesture recognition.
-
Predictive Tracking:
- Anticipate the next positions of hand landmarks when frames are dropped or occlusions occur.
-
Gesture Segmentation:
- Use velocity and acceleration estimates to segment continuous hand movements into discrete gestures.
-
Anomaly Detection:
- Detect sudden or unusual movements by monitoring the residuals (innovations) of the Kalman filter.
-
Fusion of Multiple Sensors:
- Combine data from cameras and inertial measurement units (IMUs) in a Kalman filter framework.
-
Time Series Analysis:
- Analyze temporal patterns in hand movements for activity recognition.
-
Adaptive Filtering:
- Implement Extended Kalman Filters or Unscented Kalman Filters for nonlinear dynamics involved in complex hand motions.
-
Handwriting Recognition:
- Track the fine movements of fingers for recognizing written characters in the air.
-
Virtual Reality (VR) and Augmented Reality (AR):
- Provide stable hand tracking for interaction in virtual environments.
-
Robotics Control:
- Facilitate human-robot interaction by interpreting hand gestures to control robotic systems.
By cleaning up the code, focusing on the key functionalities, and considering the suggested modifications, you can improve hand detection, enhance performance, and explore the versatility of the Kalman filter in various applications related to hand activity recognition.