| import os |
| import torch |
| import numpy as np |
| from PIL import Image |
| from sklearn.decomposition import PCA |
| from math import sqrt |
| from torchvision import transforms |
| import matplotlib.pyplot as plt |
| from open_clip.transform import ResizeLongest, _convert_to_rgb, ToTensor, Normalize |
| from torchvision.transforms import InterpolationMode |
| |
| torch.manual_seed(42) |
| np.random.seed(42) |
|
|
| |
| mean = [0.485, 0.456, 0.406] |
| std = [0.229, 0.224, 0.225] |
| target_size = (560, 560) |
|
|
| |
| normalize = Normalize(mean=mean, std=std) |
| DINO_transform = transforms.Compose([ |
| transforms.Resize((560,560),interpolation=InterpolationMode.BILINEAR), |
| _convert_to_rgb, |
| ToTensor(), |
| normalize |
| ]) |
|
|
| |
| def plot_pca(f, path, target_size): |
| """ |
| Visualize PCA for the given features. |
| |
| Args: |
| f (numpy.ndarray): Feature array of shape [N, D]. |
| path (str): Path to save the PCA visualization. |
| target_size (tuple): Target size of the output image. |
| """ |
| pca = PCA(n_components=3) |
| pca.fit(f) |
| pca_img = pca.transform(f) |
| h = w = int(sqrt(pca_img.shape[0])) |
| pca_img = pca_img.reshape(h, w, 3) |
| pca_img_min = pca_img.min(axis=(0, 1)) |
| pca_img_max = pca_img.max(axis=(0, 1)) |
| pca_img = (pca_img - pca_img_min) / (pca_img_max - pca_img_min + 1e-8) |
| pca_img = Image.fromarray((pca_img * 255).astype(np.uint8)) |
| pca_img = transforms.Resize(target_size, interpolation=transforms.InterpolationMode.NEAREST)(pca_img) |
| pca_img.save(path) |
|
|
| |
| def build_DINOv2(): |
| model_name = 'dinov2_vitb14_reg' |
| hub_path = '/mnt/SSD8T/home/wjj/.cache/torch/hub/facebookresearch_dinov2_main' |
| try: |
| vfm = torch.hub.load(hub_path, model_name, source='local').half() |
| except Exception as e: |
| raise RuntimeError(f"Failed to load DINOv2 model '{model_name}': {e}") |
| return vfm |
|
|
| |
| def visualize_dinov2_pca(image_path, output_dir): |
| """ |
| Visualize PCA for DINOv2 features. |
| |
| Args: |
| image_path (str): Path to the input image. |
| output_dir (str): Directory to save the PCA visualization. |
| """ |
| |
| if not os.path.exists(output_dir): |
| os.makedirs(output_dir) |
|
|
| |
| device = "cuda" if torch.cuda.is_available() else "cpu" |
| dino = build_DINOv2().to(device) |
|
|
| |
| image = Image.open(image_path) |
| image_tensor = DINO_transform(image).unsqueeze(0).to(torch.float16).to(device) |
|
|
| |
| with torch.no_grad(): |
| dino_feats_raw = dino.get_intermediate_layers(image_tensor, reshape=True)[0] |
| dino_feats_raw = dino_feats_raw.flatten(start_dim=-2).transpose(-2, -1) |
|
|
| |
| dino_feats_np = dino_feats_raw[0].cpu().numpy() |
|
|
| |
| pca_path = os.path.join(output_dir, "dinov2_pca.png") |
| plot_pca(dino_feats_np, pca_path, target_size) |
|
|
| print(f"PCA visualization saved at: {pca_path}") |
|
|
| |
| if __name__ == "__main__": |
| image_path = "demo_images/bird4.jpg" |
| output_dir = "dinov2_vis" |
| visualize_dinov2_pca(image_path, output_dir) |