Views
No views yet
i3d_r50 architecture from PyTorchVideo. The I3D model uses a ResNet-50 backbone inflated to 3D convolutions to capture both spatial and temporal features from videos. It was originally pretrained on the Kinetics-400 dataset, which contains ~306,245 short videos across 400 human action classes (e.g., running, dancing, cooking).arrest, Explosion, Fight, normal, roadaccidents, shooting, Stealing, vandalism. During finetuning, the final fully connected layer was modified to output 8 classes, and a Dropout layer (p=0.3) was added to reduce overfitting. The finetuned weights are stored in i3d_ucf_finetuned.pth (109 MB) and can be downloaded from this repository.arrest, Explosion, Fight, normal, roadaccidents, shooting, Stealing, vandalism.

1import torch
2import cv2
3import numpy as np
4import torch.nn as nn
5from huggingface_hub import hf_hub_download
6
7# Define the model
8def load_i3d_ucf_finetuned(repo_id="Ahmeddawood0001/i3d_ucf_finetuned", filename="i3d_ucf_finetuned.pth"):
9 class I3DClassifier(nn.Module):
10 def __init__(self, num_classes):
11 super(I3DClassifier, self).__init__()
12 self.i3d = torch.hub.load('facebookresearch/pytorchvideo', 'i3d_r50', pretrained=True)
13 self.dropout = nn.Dropout(0.3)
14 self.i3d.blocks[6].proj = nn.Linear(2048, num_classes)
15 def forward(self, x):
16 x = self.i3d(x)
17 x = self.dropout(x)
18 return x
19 device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
20 model = I3DClassifier(num_classes=8).to(device)
21 weights_path = hf_hub_download(repo_id=repo_id, filename=filename)
22 model.load_state_dict(torch.load(weights_path))
23 model.eval()
24 return model
25
26# Define frame extraction function
27def extract_frames(video_path, max_frames=32, frame_size=(224, 224)):
28 cap = cv2.VideoCapture(video_path)
29 frames = []
30 while len(frames) < max_frames:
31 ret, frame = cap.read()
32 if not ret:
33 break
34 frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
35 frame = cv2.resize(frame, frame_size)
36 frames.append(frame)
37 while len(frames) < max_frames:
38 frames.append(frames[-1])
39 frames = frames[:max_frames]
40 frames = np.stack(frames)
41 frames = torch.from_numpy(frames).permute(0, 3, 1, 2).float() / 255.0
42 frames = frames.permute(1, 0, 2, 3)
43 cap.release()
44 return frames
45
46# Define classification function
47def classify_video(video_path, model, labels):
48 frames = extract_frames(video_path)
49 frames = frames.unsqueeze(0).to(device)
50 with torch.no_grad():
51 outputs = model(frames)
52 probabilities = torch.softmax(outputs, dim=1)
53 predicted_idx = torch.argmax(probabilities, dim=1).item()
54 predicted_label = labels[predicted_idx]
55 confidence = probabilities[0, predicted_idx].item()
56 return predicted_label, confidence
57
58# Example usage
59device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
60labels = ["arrest", "Explosion", "Fight", "normal", "roadaccidents", "shooting", "Stealing", "vandalism"]
61model = load_i3d_ucf_finetuned()
62video_path = "path/to/your/video.mp4" # Replace with your video path
63predicted_label, confidence = classify_video(video_path, model, labels)
64print(f"Video: {video_path}")
65print(f"Predicted Label: {predicted_label}")
66
67print(f"Confidence: {confidence:.4f}")