import os import numpy as np from PIL import Image import matplotlib.pyplot as plt from sklearn.manifold import TSNE import torch import torchvision.transforms as transforms from mpl_toolkits.mplot3d import Axes3D from tqdm import tqdm import clip # For CLIP model def load_models(device): """Load both DINOv2 and CLIP models""" # DINOv2 dinov2 = torch.hub.load('facebookresearch/dinov2', 'dinov2_vitb14').to(device).eval() # CLIP clip_model, clip_preprocess = clip.load("ViT-B/32", device=device) return { 'dinov2': dinov2, 'clip': clip_model, 'clip_preprocess': clip_preprocess } def load_frames(folder_path, frame_ext='.png'): frame_files = sorted( [f for f in os.listdir(folder_path) if f.endswith(frame_ext)], key=lambda x: int(x.split('.')[0])) return [Image.open(os.path.join(folder_path, f)).convert('RGB') for f in tqdm(frame_files, desc="Loading frames")] def extract_embeddings(frames, model_dict, model_type, batch_size=8, device='cuda'): embeddings = [] with torch.no_grad(): if model_type == 'dinov2': transform = transforms.Compose([ transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), ]) for i in tqdm(range(0, len(frames), batch_size), desc="Extracting DINOv2 embeddings"): batch = torch.stack([transform(frames[j]) for j in range(i, min(i+batch_size, len(frames)))]).to(device) outputs = model_dict['dinov2'](batch) embeddings.append(outputs.cpu().numpy()) elif model_type == 'clip': for i in tqdm(range(0, len(frames), batch_size), desc="Extracting CLIP embeddings"): batch = [model_dict['clip_preprocess'](frames[j]) for j in range(i, min(i+batch_size, len(frames)))] batch = torch.stack(batch).to(device) outputs = model_dict['clip'].encode_image(batch) embeddings.append(outputs.cpu().numpy()) return np.concatenate(embeddings) def visualize_tsne(embeddings, title_suffix="", perplexity=15): plt.figure(figsize=(20, 8)) # 2D t-SNE plt.subplot(1, 2, 1) tsne_2d = TSNE(n_components=2, perplexity=perplexity, random_state=42) emb_2d = tsne_2d.fit_transform(embeddings) plt.scatter(emb_2d[:, 0], emb_2d[:, 1], c=range(len(embeddings)), cmap='viridis', alpha=0.7) plt.colorbar(label='Frame Number') plt.title(f'2D t-SNE {title_suffix}') # 3D t-SNE ax = plt.subplot(1, 2, 2, projection='3d') tsne_3d = TSNE(n_components=3, perplexity=perplexity, random_state=42) emb_3d = tsne_3d.fit_transform(embeddings) sc = ax.scatter(emb_3d[:, 0], emb_3d[:, 1], emb_3d[:, 2], c=range(len(embeddings)), cmap='viridis', alpha=0.7) plt.colorbar(sc, label='Frame Number') ax.set_title(f'3D t-SNE {title_suffix}') plt.tight_layout() plt.show() def main(): import argparse parser = argparse.ArgumentParser() parser.add_argument('folder_path', type=str) parser.add_argument('--ext', type=str, default='.png') parser.add_argument('--batch_size', type=int, default=8) parser.add_argument('--perplexity', type=int, default=15) args = parser.parse_args() device = 'cuda' if torch.cuda.is_available() else 'cpu' print(f"Using device: {device}") # Load models print("Loading models...") models = load_models(device) frames = load_frames(args.folder_path, args.ext) # DINOv2 Visualization print("\nProcessing DINOv2 embeddings...") dinov2_emb = extract_embeddings(frames, models, 'dinov2', args.batch_size, device) visualize_tsne(dinov2_emb, "(DINOv2)", args.perplexity) # CLIP Visualization print("\nProcessing CLIP embeddings...") clip_emb = extract_embeddings(frames, models, 'clip', args.batch_size, device) visualize_tsne(clip_emb, "(CLIP)", args.perplexity) if __name__ == '__main__': main()