Function to estimate pose for a single person and recognize activity
def estimate_pose_on_person(cropped_image):
with mp_pose.Pose(min_detection_confidence=0.5, min_tracking_confidence=0.5) as pose:
image_rgb = cv2.cvtColor(cropped_image, cv2.COLOR_BGR2RGB)
results = pose.process(image_rgb)
code
# Activity recognition based on pose landmarks
activity = recognize_activity(results.pose_landmarks)
if results.pose_landmarks:
mp_drawing.draw_landmarks(cropped_image, results.pose_landmarks, mp_pose.POSE_CONNECTIONS)
return cropped_image, activity
Function to recognize activities based on pose landmarks
def recognize_activity(landmarks):
if not landmarks:
return "Unknown"
code
# Example simple rule-based activity recognition
# You can extend this to train an ML model on top of pose data
# Sample landmark checks for walking, lifting, digging
# You will have to add further refinement for real use cases
left_shoulder = landmarks.landmark[mp_pose.PoseLandmark.LEFT_SHOULDER].y
right_shoulder = landmarks.landmark[mp_pose.PoseLandmark.RIGHT_SHOULDER].y
left_hip = landmarks.landmark[mp_pose.PoseLandmark.LEFT_HIP].y
right_hip = landmarks.landmark[mp_pose.PoseLandmark.RIGHT_HIP].y
if abs(left_shoulder - right_shoulder) < 0.05 and abs(left_hip - right_hip) < 0.05:
return "Standing"
elif left_shoulder < left_hip and right_shoulder < right_hip:
return "Digging"
else:
return "Walking"
Function to handle each frame and perform multi-person pose estimation
Assistant
def process_frame(frame):
# Use YOLOv5 to detect persons in the frame
results = model(frame)
code
# Get detection results as pandas dataframe
detections = results.pandas().xyxy[0] # Bounding boxes, confidence, and class predictions
cropped_images = []
bboxes = []
activities = []
for _, row in detections.iterrows():
if row['name'] == 'person': # Ensure the detected class is 'person'
x1, y1, x2, y2 = int(row['xmin']), int(row['ymin']), int(row['xmax']), int(row['ymax'])
cropped_image = frame[y1:y2, x1:x2]
cropped_images.append(cropped_image)
bboxes.append((x1, y1, x2, y2))
# Use multithreading to process pose estimation for each person detected
with concurrent.futures.ThreadPoolExecutor() as executor:
results = list(executor.map(estimate_pose_on_person, cropped_images))
# Draw bounding boxes, pose landmarks, and activity labels on the original frame
for idx, (cropped, activity) in enumerate(results):
x1, y1, x2, y2 = bboxes[idx]
frame[y1:y2, x1:x2] = cropped
# Draw the bounding box for each person
cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
# Put the activity text label
cv2.putText(frame, activity, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (36,255,12), 2)
return frame
Open the video stream (replace with webcam or video file path)
cap = cv2.VideoCapture('/Users/apple/Movies/hiv00032.mp4')
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
code
# Process the current frame
output_frame = process_frame(frame)
# Show the processed frame with bounding boxes, pose landmarks, and activity labels
cv2.imshow('Activity Recognition', output_frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
write steps and code to optimize the algorithm with code to implement object tracking and recognition of multiple object in the video , activity recognition of the object . first compress losslessly with out loosing the quality and cropped the video to remove unnessary things . focus on the moving pixels or objects than the stationary pixels and objects . write a very optimixed code
Optimizing your activity recognition pipeline involves several key steps:
Video Preprocessing:
Lossless Compression: Compress the video without losing quality to reduce storage and improve processing speed.
Cropping: Remove unnecessary parts of the video frame to focus on areas with movement.
Object Tracking:
Implement object tracking to maintain consistent identities across frames, reducing the need for repeated detections and improving efficiency.
Optimized Processing:
Focus processing on moving objects by leveraging background subtraction or motion detection.
Utilize multithreading or asynchronous processing to handle multiple tasks concurrently.
Activity Recognition:
Enhance activity recognition by using more sophisticated models or rule-based systems tailored to your specific use case.
Below are the detailed steps and optimized code implementation integrating these optimizations.
Step 1: Install Required Libraries
Ensure you have the necessary libraries installed. You can install any missing libraries using pip:
Note: For object tracking, we'll use the SORT (Simple Online and Realtime Tracking) algorithm. You might need to download the SORT repository or implement a similar tracking mechanism.
Step 2: Video Preprocessing
a. Lossless Compression:
Using OpenCV, you can read and write videos without loss. However, to ensure losslessness, use codecs that support it, such as FFV1 or H264 in lossless mode.
b. Cropping to Focus on Moving Regions:
We'll use background subtraction to identify moving objects and crop the frame accordingly.
Step 3: Implement Object Tracking with SORT
Integrate the SORT algorithm to track detected persons across frames. This reduces the number of detections needed and maintains consistent IDs for each person, which is beneficial for activity recognition.
Step 4: Optimized Processing and Activity Recognition
Process only the regions with detected/moving persons, perform pose estimation, and recognize activities. Utilize multithreading to handle pose estimations concurrently.
Optimized Code Implementation
Below is the optimized code incorporating all the above steps:
python
Explanation of Optimizations
Lossless Compression:
FFmpeg: The compress_video_lossless function uses FFmpeg to compress the video using the ffv1 codec, which is lossless. Make sure FFmpeg is installed on your system and accessible via the command line.
Advantages: Reduces file size without compromising quality, leading to faster read/write operations.
Cropping and Motion Focus:
Background Subtraction: Using cv2.createBackgroundSubtractorMOG2 to identify moving regions, which helps in focusing processing on areas with activity.
Contour Detection: Identifies significant moving objects by filtering out small movements based on contour area.
Object Tracking with SORT:
SORT: This algorithm provides real-time tracking of multiple objects with minimal computational overhead.
Benefits: Maintains consistent object IDs across frames, reducing the need for re-detection and enabling more accurate activity tracking.
Multithreading for Pose Estimation:
ThreadPoolExecutor: Utilizes multiple threads to perform pose estimation concurrently on detected persons, significantly speeding up processing times.
Efficient Detection:
Selective Detection: By only processing moving regions and tracked objects, the algorithm reduces unnecessary computations on stationary or irrelevant parts of the frame.
Video Writing:
Optimized Writing: Writing the processed frames to a new video file allows for later review and further processing if needed.
Real-time Feedback:
Progress Updates: Prints processing progress every 30 frames, which is useful for monitoring during long video processing tasks.
Additional Recommendations
Hardware Acceleration:
Utilize GPUs for model inference if available. PyTorch can leverage CUDA for faster processing.
Example:
python
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model.to(device)
Ensure that tensors and models are moved to the appropriate device.
Advanced Activity Recognition:
Implement more sophisticated models (e.g., LSTM, Transformer-based) trained on pose sequences for better activity classification.
Incorporate temporal information across frames to improve accuracy.
Caching and Reuse:
Cache intermediate results, such as pose landmarks, to avoid redundant computations if the same objects persist across multiple frames.
Batch Processing:
Process multiple frames or multiple detections in batches to leverage vectorized operations and further speed up processing.
Error Handling and Optimization:
Add robust error handling to manage cases where detection or pose estimation fails.
Profile the code to identify and optimize any remaining bottlenecks.
Flexible Configuration:
Externalize configuration parameters (e.g., confidence thresholds, codec choices) to allow easy adjustments without modifying the code.
By implementing the above optimizations, your activity recognition pipeline should become significantly more efficient, capable of handling multiple objects with real-time performance while maintaining high accuracy and quality.
import torch
import cv2
import mediapipe as mp
import numpy as np
import concurrent.futures
from sort import Sort # Ensure SORT is installed and accessible
import os
# Initialize YOLOv5 model
model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True)
model.conf = 0.5 # Confidence threshold
model.classes = [0] # Only detect 'person' class (class 0)
# Initialize MediaPipe Pose
mp_pose = mp.solutions.pose
mp_drawing = mp.solutions.drawing_utils
# Initialize SORT tracker
tracker = Sort(max_age=30, min_hits=3, iou_threshold=0.3)
# Initialize Background Subtractor for Motion Detection
bg_subtractor = cv2.createBackgroundSubtractorMOG2(history=500, detectShadows=False)
# Function to recognize activities based on pose landmarks
def recognize_activity(landmarks):
if not landmarks:
return "Unknown"
# Example simple rule-based activity recognition
# Extend this with more conditions or a trained model
left_shoulder = landmarks.landmark[mp_pose.PoseLandmark.LEFT_SHOULDER].y
right_shoulder = landmarks.landmark[mp_pose.PoseLandmark.RIGHT_SHOULDER].y
left_hip = landmarks.landmark[mp_pose.PoseLandmark.LEFT_HIP].y
right_hip = landmarks.landmark[mp_pose.PoseLandmark.RIGHT_HIP].y
if abs(left_shoulder - right_shoulder) < 0.05 and abs(left_hip - right_hip) < 0.05:
return "Standing"
elif left_shoulder < left_hip and right_shoulder < right_hip:
return "Digging"
else:
return "Walking"
# Function to estimate pose and recognize activity
def estimate_pose_on_person(cropped_image):
with mp_pose.Pose(min_detection_confidence=0.5, min_tracking_confidence=0.5) as pose:
image_rgb = cv2.cvtColor(cropped_image, cv2.COLOR_BGR2RGB)
results = pose.process(image_rgb)
activity = recognize_activity(results.pose_landmarks)
if results.pose_landmarks:
mp_drawing.draw_landmarks(cropped_image, results.pose_landmarks, mp_pose.POSE_CONNECTIONS)
return cropped_image, activity
# Function to preprocess the frame (lossless operations are handled by OpenCV)
def preprocess_frame(frame):
# Apply background subtraction to get the foreground mask
fg_mask = bg_subtractor.apply(frame)
# Find contours of moving objects
contours, _ = cv2.findContours(fg_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# If no movement is detected, return None to skip processing
if not contours:
return None
# Create a mask for moving regions
moving_mask = np.zeros_like(fg_mask)
for contour in contours:
if cv2.contourArea(contour) > 500: # Filter small movements
cv2.drawContours(moving_mask, [contour], -1, 255, -1)
# Apply the mask to the frame
cropped_frame = cv2.bitwise_and(frame, frame, mask=moving_mask)
return cropped_frame
# Function to process each frame
def process_frame(frame):
preprocessed = preprocess_frame(frame)
if preprocessed is None:
return frame # Return original frame if no movement detected
# Detect persons using YOLOv5
results = model(preprocessed)
detections = results.xyxy[0].cpu().numpy() # [x1, y1, x2, y2, confidence, class]
dets = []
for *box, conf, cls in detections:
dets.append([box[0], box[1], box[2], box[3], conf])
dets = np.array(dets)
tracked_objects = tracker.update(dets)
cropped_images = []
bboxes = []
object_ids = []
for obj in tracked_objects:
x1, y1, x2, y2, obj_id = obj
x1, y1, x2, y2 = map(int, [x1, y1, x2, y2])
cropped = frame[y1:y2, x1:x2]
cropped_images.append(cropped)
bboxes.append((x1, y1, x2, y2))
object_ids.append(int(obj_id))
activities = []
# Use multithreading for pose estimation
with concurrent.futures.ThreadPoolExecutor() as executor:
results = list(executor.map(estimate_pose_on_person, cropped_images))
for idx, (cropped, activity) in enumerate(results):
x1, y1, x2, y2 = bboxes[idx]
obj_id = object_ids[idx]
frame[y1:y2, x1:x2] = cropped
# Draw bounding box with object ID
cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(frame, f'ID: {obj_id}', (x1, y1 - 25), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 0, 0), 2)
# Put the activity text label
cv2.putText(frame, activity, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (36, 255, 12), 2)
return frame
# Function to compress video losslessly using FFmpeg
def compress_video_lossless(input_path, output_path):
# Ensure FFmpeg is installed on your system
command = f'ffmpeg -i "{input_path}" -c:v ffv1 -c:a copy "{output_path}" -y'
os.system(command)
# Main function
def main():
input_video_path = '/Users/apple/Movies/hiv00032.mp4'
compressed_video_path = '/Users/apple/Movies/hiv00032_compressed.mkv'
# Step 1: Compress the video losslessly
print("Compressing video...")
compress_video_lossless(input_video_path, compressed_video_path)
print("Compression completed.")
# Step 2: Open the compressed video
cap = cv2.VideoCapture(compressed_video_path)
if not cap.isOpened():
print("Error: Could not open video.")
return
# Get video properties for writing output
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = cap.get(cv2.CAP_PROP_FPS)
# Optional: Write the output to a new video file
output_video_path = '/Users/apple/Movies/hiv00032_annotated.avi'
fourcc = cv2.VideoWriter_fourcc(*'XVID') # Use a lossless codec if needed
out = cv2.VideoWriter(output_video_path, fourcc, fps, (frame_width, frame_height))
frame_count = 0
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
print("Processing video frames...")
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
# Process the frame
output_frame = process_frame(frame)
# Display the frame
cv2.imshow('Activity Recognition', output_frame)
# Write the frame to the output video
out.write(output_frame)
frame_count += 1
if frame_count % 30 == 0:
print(f"Processed {frame_count}/{total_frames} frames.")
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
out.release()
cv2.destroyAllWindows()
print("Processing completed.")
if __name__ == "__main__":
main()