vivek9chavan commited on
Commit
12a3802
·
verified ·
1 Parent(s): 65f6d12

Update dino_processor.py

Browse files
Files changed (1) hide show
  1. dino_processor.py +37 -54
dino_processor.py CHANGED
@@ -1,4 +1,4 @@
1
- # dino_processor.py
2
 
3
  import os
4
  import cv2
@@ -11,21 +11,19 @@ from sklearn.decomposition import PCA
11
  from sklearn.cluster import KMeans
12
  from scipy.spatial.distance import cdist
13
  import matplotlib.pyplot as plt
14
- import shutil # For cleaning up temporary directories
 
15
 
16
- # This will import the ViT model definitions from the other file
17
  import vision_transformer as vits
18
 
19
- # --- Helper functions from your script (no changes needed) ---
20
- # (extract_frames, compute_embeddings, select_representative_frames, generate_attention_maps)
21
- # I will copy them here for completeness, but you can just leave them as they are.
22
 
23
- def extract_frames(video_path, output_dir, fps=5):
24
  frames_dir = os.path.join(output_dir, "frames")
25
  os.makedirs(frames_dir, exist_ok=True)
26
  cap = cv2.VideoCapture(video_path)
27
  video_fps = cap.get(cv2.CAP_PROP_FPS)
28
- frame_interval = int(video_fps / fps)
29
  frame_paths = []
30
  frame_count = 0
31
  extracted_count = 0
@@ -40,7 +38,7 @@ def extract_frames(video_path, output_dir, fps=5):
40
  extracted_count += 1
41
  frame_count += 1
42
  cap.release()
43
- print(f"Extracted {len(frame_paths)} frames.")
44
  return frame_paths
45
 
46
  def compute_embeddings(frame_paths, model, device, batch_size=32):
@@ -62,20 +60,21 @@ def compute_embeddings(frame_paths, model, device, batch_size=32):
62
  embeddings.append(batch_embeddings.cpu().numpy())
63
  return np.concatenate(embeddings, axis=0), frame_names
64
 
65
- def select_representative_frames(embeddings, frame_names, n_clusters=3, pca_dim=32):
 
 
 
66
  pca = PCA(n_components=pca_dim, svd_solver='full', random_state=404543)
67
  pca_results = pca.fit_transform(embeddings)
68
  kmeans = KMeans(n_clusters=n_clusters, random_state=404543, n_init=10)
69
  kmeans.fit(pca_results)
70
  distances = cdist(kmeans.cluster_centers_, pca_results, 'euclidean')
71
- selected_frames = []
72
- for i in range(n_clusters):
73
- closest_point_idx = np.argmin(distances[i])
74
- selected_frames.append(frame_names[closest_point_idx])
75
- print(f"Selected frames: {selected_frames}")
76
  return selected_frames
77
 
78
- def generate_attention_maps(frame_path, model, device, output_dir, frame_name):
79
  img = Image.open(frame_path).convert('RGB')
80
  original_img = np.array(img)
81
  original_height, original_width = img.height, img.width
@@ -94,11 +93,7 @@ def generate_attention_maps(frame_path, model, device, output_dir, frame_name):
94
  attention = attention.reshape(nh, w_featmap, h_featmap)
95
  attention = nn.functional.interpolate(attention.unsqueeze(0), scale_factor=patch_size, mode="nearest")[0].cpu().numpy()
96
 
97
- # Save attention map
98
- attn_path = os.path.join(output_dir, f"{frame_name}_attn.png")
99
- plt.imsave(attn_path, np.sum(attention, axis=0), cmap='inferno', format='png')
100
-
101
- # Save overlay
102
  overlay_path = os.path.join(output_dir, f"{frame_name}_overlay.png")
103
  attention_map = np.sum(attention, axis=0)
104
  attention_map = (attention_map - np.min(attention_map)) / (np.max(attention_map) - np.min(attention_map))
@@ -108,59 +103,47 @@ def generate_attention_maps(frame_path, model, device, output_dir, frame_name):
108
  overlay = cv2.addWeighted(original_img, 0.5, cv2.resize(attention_colored, (original_width, original_height)), 0.5, 0)
109
  Image.fromarray(overlay).save(overlay_path)
110
 
111
- return overlay_path, attn_path
112
-
113
- # --- Main orchestrator function ---
114
- def process_video_with_dino(video_path, output_dir="dino_output"):
115
- """
116
- Main function to process a video and generate DINO attention maps.
117
-
118
- Args:
119
- video_path (str): Path to the input video.
120
- output_dir (str): Directory to save all intermediate and final files.
121
-
122
- Returns:
123
- list: A list of tuples, where each tuple contains (overlay_path, attention_map_path).
124
- """
125
- # Clean up previous runs and create output directory
126
- if os.path.exists(output_dir):
127
- shutil.rmtree(output_dir)
128
- os.makedirs(output_dir, exist_ok=True)
129
 
 
 
 
130
  device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
131
-
132
- # Build model (using vit_small with patch size 8 as a default)
133
  patch_size = 8
134
  model = vits.vit_small(patch_size=patch_size, num_classes=0)
135
  for p in model.parameters():
136
  p.requires_grad = False
137
  model.eval()
138
  model.to(device)
139
-
140
- # Load pretrained weights from torch.hub
141
  url = "dino_deitsmall8_300ep_pretrain/dino_deitsmall8_300ep_pretrain.pth"
142
  state_dict = torch.hub.load_state_dict_from_url(url="https://dl.fbaipublicfiles.com/dino/" + url)
143
  model.load_state_dict(state_dict, strict=True)
144
- print("DINO weights loaded successfully from torch.hub.")
 
 
 
 
 
 
 
 
 
145
 
146
- # Step 1: Extract frames
147
  frame_paths = extract_frames(video_path, output_dir)
148
  if not frame_paths:
149
  raise ValueError("No frames were extracted from the video.")
150
 
151
- # Step 2: Compute embeddings
152
  embeddings, frame_names = compute_embeddings(frame_paths, model, device)
153
-
154
- # Step 3: Select representative frames
155
  selected_frames = select_representative_frames(embeddings, frame_names)
156
 
157
- # Step 4: Generate attention maps for selected frames
158
- results = []
159
  frames_dir = os.path.join(output_dir, "frames")
160
  for frame_name in selected_frames:
161
  frame_path = os.path.join(frames_dir, frame_name)
162
  frame_name_no_ext = os.path.splitext(frame_name)[0]
163
- overlay_path, attn_path = generate_attention_maps(frame_path, model, device, output_dir, frame_name_no_ext)
164
- results.append((overlay_path, attn_path))
165
-
166
- return results
 
 
1
+ # dino_processor.py (OPTIMIZED VERSION)
2
 
3
  import os
4
  import cv2
 
11
  from sklearn.cluster import KMeans
12
  from scipy.spatial.distance import cdist
13
  import matplotlib.pyplot as plt
14
+ import shutil
15
+ from datetime import datetime
16
 
 
17
  import vision_transformer as vits
18
 
19
+ # --- Helper functions (with your new parameters) ---
 
 
20
 
21
+ def extract_frames(video_path, output_dir, fps=5): # OPTIMIZATION: Reduced FPS
22
  frames_dir = os.path.join(output_dir, "frames")
23
  os.makedirs(frames_dir, exist_ok=True)
24
  cap = cv2.VideoCapture(video_path)
25
  video_fps = cap.get(cv2.CAP_PROP_FPS)
26
+ frame_interval = int(video_fps / fps) if video_fps > 0 else 1
27
  frame_paths = []
28
  frame_count = 0
29
  extracted_count = 0
 
38
  extracted_count += 1
39
  frame_count += 1
40
  cap.release()
41
+ print(f"Extracted {len(frame_paths)} frames at {fps} FPS.")
42
  return frame_paths
43
 
44
  def compute_embeddings(frame_paths, model, device, batch_size=32):
 
60
  embeddings.append(batch_embeddings.cpu().numpy())
61
  return np.concatenate(embeddings, axis=0), frame_names
62
 
63
+ def select_representative_frames(embeddings, frame_names, n_clusters=3, pca_dim=32): # OPTIMIZATION: Reduced clusters
64
+ n_clusters = min(n_clusters, len(frame_names))
65
+ if n_clusters == 0: return []
66
+
67
  pca = PCA(n_components=pca_dim, svd_solver='full', random_state=404543)
68
  pca_results = pca.fit_transform(embeddings)
69
  kmeans = KMeans(n_clusters=n_clusters, random_state=404543, n_init=10)
70
  kmeans.fit(pca_results)
71
  distances = cdist(kmeans.cluster_centers_, pca_results, 'euclidean')
72
+ selected_frames_indices = np.argmin(distances, axis=1)
73
+ selected_frames = [frame_names[i] for i in selected_frames_indices]
74
+ print(f"Selected {len(selected_frames)} representative frames.")
 
 
75
  return selected_frames
76
 
77
+ def generate_attention_overlay(frame_path, model, device, output_dir, frame_name): # OPTIMIZATION: Renamed function
78
  img = Image.open(frame_path).convert('RGB')
79
  original_img = np.array(img)
80
  original_height, original_width = img.height, img.width
 
93
  attention = attention.reshape(nh, w_featmap, h_featmap)
94
  attention = nn.functional.interpolate(attention.unsqueeze(0), scale_factor=patch_size, mode="nearest")[0].cpu().numpy()
95
 
96
+ # Create and save ONLY the overlay
 
 
 
 
97
  overlay_path = os.path.join(output_dir, f"{frame_name}_overlay.png")
98
  attention_map = np.sum(attention, axis=0)
99
  attention_map = (attention_map - np.min(attention_map)) / (np.max(attention_map) - np.min(attention_map))
 
103
  overlay = cv2.addWeighted(original_img, 0.5, cv2.resize(attention_colored, (original_width, original_height)), 0.5, 0)
104
  Image.fromarray(overlay).save(overlay_path)
105
 
106
+ return overlay_path # OPTIMIZATION: Return only the overlay path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
 
108
+ # --- Function to load the model (no changes) ---
109
+ def load_dino_model():
110
+ print("--- Loading DINO model into memory (this happens only once) ---")
111
  device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
 
 
112
  patch_size = 8
113
  model = vits.vit_small(patch_size=patch_size, num_classes=0)
114
  for p in model.parameters():
115
  p.requires_grad = False
116
  model.eval()
117
  model.to(device)
 
 
118
  url = "dino_deitsmall8_300ep_pretrain/dino_deitsmall8_300ep_pretrain.pth"
119
  state_dict = torch.hub.load_state_dict_from_url(url="https://dl.fbaipublicfiles.com/dino/" + url)
120
  model.load_state_dict(state_dict, strict=True)
121
+ print("--- DINO model loaded successfully ---")
122
+ return model, device
123
+
124
+ # --- Main function (modified for simplified output) ---
125
+ def process_video_with_dino(video_path, model, device):
126
+ archive_dir = "dino_archive"
127
+ os.makedirs(archive_dir, exist_ok=True)
128
+ timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
129
+ output_dir = os.path.join(archive_dir, timestamp)
130
+ os.makedirs(output_dir, exist_ok=True)
131
 
 
132
  frame_paths = extract_frames(video_path, output_dir)
133
  if not frame_paths:
134
  raise ValueError("No frames were extracted from the video.")
135
 
 
136
  embeddings, frame_names = compute_embeddings(frame_paths, model, device)
 
 
137
  selected_frames = select_representative_frames(embeddings, frame_names)
138
 
139
+ # OPTIMIZATION: Results is now a simple list of overlay paths
140
+ overlay_paths = []
141
  frames_dir = os.path.join(output_dir, "frames")
142
  for frame_name in selected_frames:
143
  frame_path = os.path.join(frames_dir, frame_name)
144
  frame_name_no_ext = os.path.splitext(frame_name)[0]
145
+ overlay_path = generate_attention_overlay(frame_path, model, device, output_dir, frame_name_no_ext)
146
+ overlay_paths.append(overlay_path)
147
+
148
+ shutil.rmtree(frames_dir)
149
+ return overlay_paths