import cv2
import mediapipe as mp
import numpy as np
# Initialize MediaPipe Pose.
mp_drawing = mp.solutions.drawing_utils
mp_pose = mp.solutions.pose
# Define a KalmanFilter class for 2D points.
class KalmanFilter2D:
def __init__(self, dt=1, process_noise=1e-4, measurement_noise=1e-1):
# State vector [x, y, dx, dy]
self.state = np.zeros((4, 1))
# State transition matrix
self.F = np.array([[1, 0, dt, 0],
[0, 1, 0, dt],
[0, 0, 1, 0 ],
[0, 0, 0, 1 ]])
# Measurement matrix
self.H = np.array([[1, 0, 0, 0],
[0, 1, 0, 0]])
# Process noise covariance
self.Q = process_noise * np.eye(4)
# Measurement noise covariance
self.R = measurement_noise * np.eye(2)
# Estimate covariance matrix
self.P = np.eye(4)
def predict(self):
# Predict the next state
self.state = np.dot(self.F, self.state)
self.P = np.dot(self.F, np.dot(self.P, self.F.T)) + self.Q
return self.state[:2]
def update(self, measurement):
z = np.array(measurement).reshape(2, 1)
y = z - np.dot(self.H, self.state) # Measurement residual
S = np.dot(self.H, np.dot(self.P, self.H.T)) + self.R # Residual covariance
K = np.dot(np.dot(self.P, self.H.T), np.linalg.inv(S)) # Kalman gain
self.state = self.state + np.dot(K, y)
I = np.eye(self.F.shape[1])
self.P = np.dot((I - np.dot(K, self.H)), self.P)
return self.state[:2]
def main():
# Initialize video capture
video_path = 'input_video.mp4' # Replace with your video file
cap = cv2.VideoCapture(video_path)
# Initialize MediaPipe Pose
pose = mp_pose.Pose(static_image_mode=False,
model_complexity=1,
smooth_landmarks=True,
enable_segmentation=False,
min_detection_confidence=0.5,
min_tracking_confidence=0.5)
# Initialize Kalman Filters for all 33 landmarks
kalman_filters = {}
for lm_id in range(33):
kalman_filters[lm_id] = KalmanFilter2D(dt=1/30) # Assuming 30 FPS
# Activity recognition variables
# Example: simple step detection based on ankle movement
left_ankle_prev = None
right_ankle_prev = None
steps = {'left': 0, 'right': 0}
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
# Convert the BGR image to RGB and process with MediaPipe
img_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
results = pose.process(img_rgb)
if results.pose_landmarks:
filtered_landmarks = []
for lm_id, lm in enumerate(results.pose_landmarks.landmark):
# Get normalized coordinates
x, y = lm.x, lm.y
# Convert to pixel coordinates
h, w, _ = frame.shape
meas_x, meas_y = int(x * w), int(y * h)
# Update Kalman Filter
kf = kalman_filters[lm_id]
kf.predict()
filtered = kf.update([meas_x, meas_y])
filtered_x, filtered_y = int(filtered[0,0]), int(filtered[1,0])
filtered_landmarks.append((filtered_x, filtered_y))
# Draw original landmarks in red
cv2.circle(frame, (meas_x, meas_y), 5, (0, 0, 255), -1)
# Draw filtered landmarks in green
cv2.circle(frame, (filtered_x, filtered_y), 5, (0, 255, 0), -1)
# Example activity recognition: step detection
left_ankle = filtered_landmarks[mp_pose.PoseLandmark.LEFT_ANKLE.value]
right_ankle = filtered_landmarks[mp_pose.PoseLandmark.RIGHT_ANKLE.value]
# Detect steps by vertical movement
if left_ankle_prev:
dy = left_ankle[1] - left_ankle_prev[1]
if dy > 20:
steps['left'] += 1
left_ankle_prev = left_ankle
if right_ankle_prev:
dy = right_ankle[1] - right_ankle_prev[1]
if dy > 20:
steps['right'] += 1
right_ankle_prev = right_ankle
# Display step counts
cv2.putText(frame, f"Left Steps: {steps['left']}", (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)
cv2.putText(frame, f"Right Steps: {steps['right']}", (10, 70),
cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)
# Draw skeleton for visualization
mp_drawing.draw_landmarks(
frame, results.pose_landmarks, mp_pose.POSE_CONNECTIONS,
mp_drawing.DrawingSpec(color=(255, 255, 255), thickness=2, circle_radius=2),
mp_drawing.DrawingSpec(color=(0, 255, 255), thickness=2, circle_radius=2)
)
# Display the resulting frame
cv2.imshow('Kalman Filter Activity Recognition', frame)
# Press 'q' to exit
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Release resources
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
main()