xiaomoguhzz commited on
Commit
1bfcc6e
·
verified ·
1 Parent(s): 1ae361c

Upload code/model_vis_tools/pca_dinov2.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. code/model_vis_tools/pca_dinov2.py +100 -0
code/model_vis_tools/pca_dinov2.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import numpy as np
4
+ from PIL import Image
5
+ from sklearn.decomposition import PCA
6
+ from math import sqrt
7
+ from torchvision import transforms
8
+ import matplotlib.pyplot as plt
9
+ from open_clip.transform import ResizeLongest, _convert_to_rgb, ToTensor, Normalize
10
+ from torchvision.transforms import InterpolationMode
11
+ # Ensure reproducibility
12
+ torch.manual_seed(42)
13
+ np.random.seed(42)
14
+
15
+ # Define constants
16
+ mean = [0.485, 0.456, 0.406]
17
+ std = [0.229, 0.224, 0.225]
18
+ target_size = (560, 560)
19
+
20
+ # Define transforms
21
+ normalize = Normalize(mean=mean, std=std)
22
+ DINO_transform = transforms.Compose([
23
+ transforms.Resize((560,560),interpolation=InterpolationMode.BILINEAR),
24
+ _convert_to_rgb,
25
+ ToTensor(),
26
+ normalize
27
+ ])
28
+
29
+ # PCA visualization function
30
+ def plot_pca(f, path, target_size):
31
+ """
32
+ Visualize PCA for the given features.
33
+
34
+ Args:
35
+ f (numpy.ndarray): Feature array of shape [N, D].
36
+ path (str): Path to save the PCA visualization.
37
+ target_size (tuple): Target size of the output image.
38
+ """
39
+ pca = PCA(n_components=3)
40
+ pca.fit(f)
41
+ pca_img = pca.transform(f) # n x 3
42
+ h = w = int(sqrt(pca_img.shape[0]))
43
+ pca_img = pca_img.reshape(h, w, 3)
44
+ pca_img_min = pca_img.min(axis=(0, 1))
45
+ pca_img_max = pca_img.max(axis=(0, 1))
46
+ pca_img = (pca_img - pca_img_min) / (pca_img_max - pca_img_min + 1e-8) # Normalize
47
+ pca_img = Image.fromarray((pca_img * 255).astype(np.uint8))
48
+ pca_img = transforms.Resize(target_size, interpolation=transforms.InterpolationMode.NEAREST)(pca_img)
49
+ pca_img.save(path)
50
+
51
+ # DINOv2 model loading function
52
+ def build_DINOv2():
53
+ model_name = 'dinov2_vitb14_reg'
54
+ hub_path = '/mnt/SSD8T/home/wjj/.cache/torch/hub/facebookresearch_dinov2_main'
55
+ try:
56
+ vfm = torch.hub.load(hub_path, model_name, source='local').half()
57
+ except Exception as e:
58
+ raise RuntimeError(f"Failed to load DINOv2 model '{model_name}': {e}")
59
+ return vfm
60
+
61
+ # Main function for DINOv2 PCA visualization
62
+ def visualize_dinov2_pca(image_path, output_dir):
63
+ """
64
+ Visualize PCA for DINOv2 features.
65
+
66
+ Args:
67
+ image_path (str): Path to the input image.
68
+ output_dir (str): Directory to save the PCA visualization.
69
+ """
70
+ # Ensure output directory exists
71
+ if not os.path.exists(output_dir):
72
+ os.makedirs(output_dir)
73
+
74
+ # Load DINOv2 model
75
+ device = "cuda" if torch.cuda.is_available() else "cpu"
76
+ dino = build_DINOv2().to(device)
77
+
78
+ # Load and preprocess image
79
+ image = Image.open(image_path)
80
+ image_tensor = DINO_transform(image).unsqueeze(0).to(torch.float16).to(device)
81
+
82
+ # Extract DINOv2 features
83
+ with torch.no_grad():
84
+ dino_feats_raw = dino.get_intermediate_layers(image_tensor, reshape=True)[0]
85
+ dino_feats_raw = dino_feats_raw.flatten(start_dim=-2).transpose(-2, -1) # [1, N, D]
86
+
87
+ # Prepare features for PCA
88
+ dino_feats_np = dino_feats_raw[0].cpu().numpy()
89
+
90
+ # Save PCA visualization
91
+ pca_path = os.path.join(output_dir, "dinov2_pca.png")
92
+ plot_pca(dino_feats_np, pca_path, target_size)
93
+
94
+ print(f"PCA visualization saved at: {pca_path}")
95
+
96
+ # Example usage
97
+ if __name__ == "__main__":
98
+ image_path = "demo_images/bird4.jpg" # Replace with your image path
99
+ output_dir = "dinov2_vis"
100
+ visualize_dinov2_pca(image_path, output_dir)