File size: 3,313 Bytes
1bfcc6e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | 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
# Ensure reproducibility
torch.manual_seed(42)
np.random.seed(42)
# Define constants
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
target_size = (560, 560)
# Define transforms
normalize = Normalize(mean=mean, std=std)
DINO_transform = transforms.Compose([
transforms.Resize((560,560),interpolation=InterpolationMode.BILINEAR),
_convert_to_rgb,
ToTensor(),
normalize
])
# PCA visualization function
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) # n x 3
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) # Normalize
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)
# DINOv2 model loading function
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
# Main function for DINOv2 PCA visualization
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.
"""
# Ensure output directory exists
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# Load DINOv2 model
device = "cuda" if torch.cuda.is_available() else "cpu"
dino = build_DINOv2().to(device)
# Load and preprocess image
image = Image.open(image_path)
image_tensor = DINO_transform(image).unsqueeze(0).to(torch.float16).to(device)
# Extract DINOv2 features
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) # [1, N, D]
# Prepare features for PCA
dino_feats_np = dino_feats_raw[0].cpu().numpy()
# Save PCA visualization
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}")
# Example usage
if __name__ == "__main__":
image_path = "demo_images/bird4.jpg" # Replace with your image path
output_dir = "dinov2_vis"
visualize_dinov2_pca(image_path, output_dir) |