Certainly! Below is a guide to help you run a pretrained SlowFast network for activity recognition on any video. This includes instructions on setting up the environment, downloading a pretrained model, processing a video, and obtaining predictions. Additionally, I'll provide resources where you can download sample activity recognition videos.
1. Overview of SlowFast Network
SlowFast is a video recognition model introduced by Facebook AI Research (FAIR) that captures both slow and fast features in videos, making it highly effective for action recognition tasks.
2. Setup Environment
Before running the SlowFast network, ensure you have the necessary dependencies installed.
Prerequisites
- Python 3.6+
- PyTorch 1.4+
- Other dependencies:
torchvision, opencv-python, etc.
Installation Steps
-
Clone the SlowFast Repository
The official SlowFast repository by Facebook provides all the necessary code and pretrained models.
git clone https://github.com/facebookresearch/SlowFast.git
cd SlowFast
-
Create a Virtual Environment (Optional but Recommended)
python3 -m venv slowfast_env
source slowfast_env/bin/activate
-
Install Dependencies
Install Python dependencies using requirements.txt:
pip install -r requirements.txt
Additionally, install SlowFast as a package:
python setup.py build develop
-
Install PyTorch
Visit the official PyTorch website to install the version compatible with your CUDA setup. For example:
pip install torch torchvision
3. Download a Pretrained SlowFast Model
Pretrained models are available within the SlowFast repository or can be downloaded directly from Facebook AI's Model Zoo.
For example, to download the R50 (ResNet-50 backbone) pretrained SlowFast model:
wget https://dl.fbaipublicfiles.com/slowfast/kinetics/SLOWFAST_8x8_R50.pkl
Ensure you have sufficient disk space as these models can be large (several GBs).
4. Running the Pretrained Model on a Video
Below is a Python script that demonstrates how to load a pretrained SlowFast model, preprocess a video, and perform activity recognition.
Script: slowfast_inference.py
import torch
import torchvision.transforms as transforms
import numpy as np
import cv2
import sys
import os
from slowfast.models import build_model
from slowfast.config.defaults import get_cfg
from slowfast.utils.checkpoint import load_checkpoint
from slowfast.utils.parser import load_config, parse_args
from slowfast.datasets import utils as utils
def preprocess_video(video_path, cfg):
"""
Preprocess the video and convert it into tensor as required by SlowFast model.
"""
# Read video using OpenCV
cap = cv2.VideoCapture(video_path)
frames = []
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
# Convert BGR to RGB
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frames.append(frame)
cap.release()
# Resize and crop frames
transform = transforms.Compose([
transforms.ToPILImage(),
transforms.Resize(cfg.DATA.TRAIN_CROP_SIZE),
transforms.CenterCrop(cfg.DATA.TRAIN_CROP_SIZE),
transforms.ToTensor(),
transforms.Normalize(mean=cfg.DATA.MEAN, std=cfg.DATA.STD),
])
processed_frames = [transform(frame) for frame in frames]
processed_frames = torch.stack(processed_frames) # Shape: [num_frames, C, H, W]
# Sample frames
num_frames = processed_frames.shape[0]
sample_rate = cfg.DATA.SAMPLING_RATE
clip_length = cfg.DATA.NUM_FRAMES
# Ensure enough frames
if num_frames < sample_rate * (clip_length - 1):
raise ValueError("Video is too short for the configured sampling rate and frame count.")
# Sampling frames
indices = np.arange(0, sample_rate * clip_length, sample_rate)
sampled_frames = processed_frames[indices, :, :, :]
# Add batch dimension and view as per SlowFast input
input_tensor = sampled_frames.permute(3, 0, 1, 2).unsqueeze(0) # Shape: [1, C, T, H, W]
return input_tensor
def main():
# Load configuration
cfg = get_cfg()
cfg.merge_from_file("configs/Kinetics/SLOWFAST_8x8_R50.yaml") # Update the path if necessary
cfg.freeze()
# Build the model
model = build_model(cfg)
model.eval()
# Load checkpoint
checkpoint_path = "SLOWFAST_8x8_R50.pkl" # Update if different
load_checkpoint(checkpoint_path, model, None)
# Move model to GPU if available
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = model.to(device)
# Path to your video
video_path = "path_to_your_video.mp4" # Replace with your video path
# Preprocess the video
input_tensor = preprocess_video(video_path, cfg)
input_tensor = input_tensor.to(device)
# Perform inference
with torch.no_grad():
outputs = model(input_tensor)
probabilities = torch.nn.functional.softmax(outputs, dim=1)
confidence, predicted_class = torch.max(probabilities, 1)
# Load label names
label_map = utils.load_label_mapping("data/kinetics/label_map.txt") # Update path if necessary
activity = label_map[predicted_class.item()]
print(f"Predicted Activity: {activity} with confidence {confidence.item():.4f}")
if __name__ == "__main__":
main()
Explanation of the Script
-
Configuration: Loads the SlowFast configuration file (SLOWFAST_8x8_R50.yaml). Ensure the path is correct.
-
Model Building: Builds the SlowFast model using the loaded configuration and loads the pretrained weights from the checkpoint file.
-
Video Preprocessing:
- Reads the video using OpenCV.
- Converts frames from BGR to RGB.
- Applies necessary transformations (resize, crop, normalization).
- Samples frames according to the model's expected sampling rate and frame count.
- Converts frames into a tensor with the appropriate shape [Batch, Channels, Time, Height, Width].
-
Inference: Runs the preprocessed video through the model to obtain class probabilities and identifies the predicted activity.
-
Label Mapping: Maps the predicted class index to the actual activity label using a label map file.
Important Notes
-
Configuration File: Ensure that the configuration file path (configs/Kinetics/SLOWFAST_8x8_R50.yaml) is correct. These files are part of the SlowFast repository.
-
Label Mapping: You need a label map file that maps class indices to activity names. This is typically available in the dataset used to train the model (e.g., Kinetics). For Kinetics-400, you can find labels here.
-
Video Path: Replace "path_to_your_video.mp4" with the path to the video you want to analyze.
-
Dependencies: Ensure all dependencies are correctly installed. Some components like slowfast.models, slowfast.config, etc., come from the SlowFast repository.
5. Downloading Sample Activity Recognition Videos
You can use videos from standard action recognition datasets or any other sources. Here are some options:
a. Kinetics Dataset
The Kinetics-400 dataset is widely used for action recognition. It contains 400 human action classes and over 300k video clips.
b. UCF101 Dataset
The UCF101 dataset consists of 13,320 videos from 101 action categories.
c. Sample Videos from YouTube
For quick testing, you can download any public video from YouTube related to activities. Here's how you can do it:
-
Find a Video: Choose a video that clearly shows a single activity or multiple activities you want to recognize.
-
Download the Video: Use tools like youtube-dl to download videos.
# Install youtube-dl if not already installed
sudo curl -L https://yt-dl.org/downloads/latest/youtube-dl -o /usr/local/bin/youtube-dl
sudo chmod a+rx /usr/local/bin/youtube-dl
# Download a video
youtube-dl -f mp4 <YouTube Video URL>
-
Use the Downloaded Video: Place the downloaded video in your working directory and update the video_path in the script accordingly.
d. Using FFmpeg to Download Example Videos
If you have sample video URLs, you can use FFmpeg to download them:
ffmpeg -i "http://path_to_video/video.mp4" -c copy path_to_save_video.mp4
Replace the URL and paths with your actual video link and desired save location.
6. Running the Inference Script
-
Ensure All Paths are Correct: Update the script with the correct paths for configuration files, checkpoint files, label maps, and your target video.
-
Execute the Script
python slowfast_inference.py
-
View the Output
The script will print the predicted activity along with the confidence score. For example:
Predicted Activity: Playing Soccer with confidence 0.8732
Troubleshooting Tips
-
CUDA Issues: If you encounter CUDA-related errors, ensure that your GPU drivers and CUDA toolkit are correctly installed and compatible with your PyTorch version.
-
Video Preprocessing Errors: Ensure the video has enough frames as required by the model's sampling rate and frame count.
-
Missing Files: Verify that all required files (configuration, checkpoint, label map) are correctly placed and paths are updated in the script.
-
Dependencies: Make sure all Python packages are installed. You can use pip install to add any missing dependencies.
Additional Resources
Conclusion
By following the steps outlined above, you should be able to run a pretrained SlowFast network on any activity recognition video. Ensure that all dependencies are correctly installed and paths are properly set in the script. For best results, use videos from standard action recognition datasets or clear public videos that showcase distinct activities.
If you encounter any issues or have further questions, feel free to ask!