Download experiments/image2image/image_similarity_all.py from jacodd/SynthField: direct link, hf CLI and curl.
- Browser
- Download file 21.1 kB
-
https://huggingface.co/datasets/jacodd/SynthField/resolve/main/experiments/image2image/image_similarity_all.py
- Command line
-
hf download hf://datasets/jacodd/SynthField/experiments/image2image/image_similarity_all.py
-
curl -L -o image_similarity_all.py https://huggingface.co/datasets/jacodd/SynthField/resolve/main/experiments/image2image/image_similarity_all.py
21.1 kB
| import torch | |
| import torch.nn.functional as F | |
| from torchvision import models, transforms | |
| from PIL import Image | |
| import numpy as np | |
| import os | |
| from pathlib import Path | |
| import matplotlib.pyplot as plt | |
| import seaborn as sns | |
| from scipy.spatial.distance import sqeuclidean | |
| from scipy import linalg | |
| from matplotlib.offsetbox import OffsetImage, AnnotationBbox | |
| class ImageSimilarityFinder: | |
| def __init__(self, model_name='resnet50', device=None): | |
| """ | |
| Initialize the image similarity finder with a vision encoder model. | |
| Args: | |
| model_name: Name of the pretrained model ('resnet50', 'vit_b_32', etc.) | |
| device: torch device (cuda or cpu) | |
| """ | |
| self.device = device if device else torch.device('cuda' if torch.cuda.is_available() else 'cpu') | |
| print(f"Using device: {self.device}") | |
| # Load pretrained model | |
| if model_name == 'resnet50': | |
| self.model = models.resnet50(pretrained=True) | |
| # Remove the final classification layer to get embeddings | |
| self.model = torch.nn.Sequential(*list(self.model.children())[:-1]) | |
| elif model_name == 'efficientnet': | |
| self.model = models.efficientnet_b0(pretrained=True) | |
| self.model = torch.nn.Sequential(*list(self.model.children())[:-1]) | |
| else: | |
| raise ValueError(f"Model {model_name} not supported") | |
| self.model = self.model.to(self.device) | |
| self.model.eval() | |
| # Image preprocessing | |
| self.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] | |
| ) | |
| ]) | |
| def get_image_embedding(self, image_path): | |
| """Extract embedding from an image.""" | |
| image = Image.open(image_path).convert('RGB') | |
| image_tensor = self.transform(image).unsqueeze(0).to(self.device) | |
| with torch.no_grad(): | |
| embedding = self.model(image_tensor) | |
| # Flatten the embedding | |
| embedding = embedding.view(embedding.size(0), -1) | |
| return embedding | |
| def compute_similarity(self, embedding1, embedding2, metric='cosine'): | |
| """ | |
| Compute similarity between two embeddings. | |
| Args: | |
| embedding1, embedding2: Image embeddings | |
| metric: 'cosine' or 'euclidean' | |
| Returns: | |
| Similarity score (0-1 for cosine) | |
| """ | |
| if metric == 'cosine': | |
| similarity = F.cosine_similarity(embedding1, embedding2, dim=1) | |
| elif metric == 'euclidean': | |
| distance = torch.norm(embedding1 - embedding2, dim=1) | |
| similarity = 1 / (1 + distance) # Convert distance to similarity | |
| else: | |
| raise ValueError(f"Metric {metric} not supported") | |
| return similarity.item() | |
| def find_similar_images(self, folder_path, metric='cosine'): | |
| """ | |
| Find similarities between all images in a folder. | |
| Args: | |
| folder_path: Path to folder containing images | |
| metric: 'cosine' or 'euclidean' | |
| Returns: | |
| Dictionary with image names and their similarity matrix | |
| """ | |
| # Get all image files | |
| image_extensions = {'.jpg', '.jpeg', '.png', '.bmp', '.gif'} | |
| image_files = [ | |
| f for f in os.listdir(folder_path) | |
| if os.path.splitext(f)[1].lower() in image_extensions | |
| ] | |
| if not image_files: | |
| print("No images found in the folder!") | |
| return None | |
| print(f"Found {len(image_files)} images: {image_files}") | |
| # Get embeddings for all images | |
| embeddings = {} | |
| print("\nExtracting embeddings...") | |
| for img_file in image_files: | |
| img_path = os.path.join(folder_path, img_file) | |
| embedding = self.get_image_embedding(img_path) | |
| embeddings[img_file] = embedding | |
| print(f" ✓ {img_file}") | |
| # Compute similarity matrix | |
| n_images = len(image_files) | |
| similarity_matrix = np.zeros((n_images, n_images)) | |
| print("\nComputing similarities...") | |
| for i, img1 in enumerate(image_files): | |
| for j, img2 in enumerate(image_files): | |
| similarity = self.compute_similarity( | |
| embeddings[img1], | |
| embeddings[img2], | |
| metric=metric | |
| ) | |
| similarity_matrix[i, j] = similarity | |
| return image_files, similarity_matrix | |
| # def plot_similarity_matrix(self, image_files, similarity_matrix, save_path=None): | |
| # """Visualize the similarity matrix as a heatmap.""" | |
| # plt.figure(figsize=(10, 8)) | |
| # sns.heatmap( | |
| # similarity_matrix, | |
| # xticklabels=image_files, | |
| # yticklabels=image_files, | |
| # annot=True, | |
| # fmt='.3f', | |
| # cmap='coolwarm', | |
| # vmin=0, | |
| # vmax=1 | |
| # ) | |
| # plt.title('Image Similarity Matrix (Cosine Similarity)') | |
| # plt.tight_layout() | |
| # if save_path: | |
| # # Create directory if it doesn't exist | |
| # os.makedirs(os.path.dirname(save_path), exist_ok=True) | |
| # plt.savefig(save_path, dpi=150, bbox_inches='tight') | |
| # print(f"\nHeatmap saved to {save_path}") | |
| # plt.show() | |
| def plot_similarity_matrix(self, image_files, similarity_matrix, folder_path, save_path=None): | |
| """Visualize the similarity matrix as a heatmap with images on the axes.""" | |
| fig, ax = plt.subplots(figsize=(12, 10)) | |
| # Create the heatmap | |
| sns.heatmap( | |
| similarity_matrix, | |
| annot=True, | |
| fmt='.3f', | |
| cmap='coolwarm', | |
| vmin=0, | |
| vmax=1, | |
| ax=ax, | |
| cbar_kws={'pad': 0.1} # Make room for images | |
| ) | |
| def add_image_anchors(axis_type, tick_positions, labels): | |
| for i, (pos, img_name) in enumerate(zip(tick_positions, labels)): | |
| # Load and thumbnail the image | |
| img_path = os.path.join('input', img_name) | |
| img = Image.open(img_path).convert('RGB') | |
| img.thumbnail((200, 200)) # Resize for the axis | |
| imagebox = OffsetImage(img, zoom=0.5) # Adjust zoom based on your DPI | |
| if axis_type == 'x': | |
| # Position image below the X-axis | |
| ab = AnnotationBbox(imagebox, (pos, 0), | |
| xybox=(0, -65), # Distance from axis | |
| xycoords=('data', 'axes fraction'), | |
| boxcoords="offset points", | |
| frameon=False) | |
| else: | |
| # Position image to the left of the Y-axis | |
| ab = AnnotationBbox(imagebox, (0, pos), | |
| xybox=(-65, 0), | |
| xycoords=('axes fraction', 'data'), | |
| boxcoords="offset points", | |
| frameon=False) | |
| ax.add_artist(ab) | |
| # Get tick positions (Seaborn centers them at 0.5, 1.5, etc.) | |
| tick_positions = np.arange(len(image_files)) + 0.5 | |
| # Add images to both axes | |
| add_image_anchors('x', tick_positions, image_files) | |
| add_image_anchors('y', tick_positions, image_files) | |
| # Remove text labels to avoid clutter | |
| ax.set_xticklabels([]) | |
| ax.set_yticklabels([]) | |
| plt.title('Visual Image Similarity Matrix', pad=20) | |
| plt.tight_layout() | |
| if save_path: | |
| os.makedirs(os.path.dirname(save_path), exist_ok=True) | |
| plt.savefig(save_path, dpi=150, bbox_inches='tight') | |
| print(f"\nHeatmap with images saved to {save_path}") | |
| plt.show() | |
| def print_similarity_results(self, image_files, similarity_matrix): | |
| """Print similarity results in a readable format.""" | |
| print("\n" + "="*80) | |
| print("IMAGE SIMILARITY RESULTS") | |
| print("="*80 + "\n") | |
| for i in range(len(image_files)): | |
| for j in range(i + 1, len(image_files)): | |
| img1 = image_files[i] | |
| img2 = image_files[j] | |
| similarity = similarity_matrix[i, j] | |
| # Create a visual representation | |
| bar_length = int(similarity * 40) | |
| bar = '█' * bar_length + '░' * (40 - bar_length) | |
| print(f"{img1} <-> {img2}") | |
| print(f" [{bar}] {similarity:.4f}") | |
| class FIDSimilarityFinder: | |
| """Compute Fréchet Inception Distance (FID) between images.""" | |
| def __init__(self, device=None): | |
| """ | |
| Initialize FID calculator using InceptionV3 model. | |
| Args: | |
| device: torch device (cuda or cpu) | |
| """ | |
| self.device = device if device else torch.device('cuda' if torch.cuda.is_available() else 'cpu') | |
| print(f"Using device: {self.device}") | |
| # Load InceptionV3 model (pretrained on ImageNet) | |
| inception = models.inception_v3(pretrained=True) | |
| inception.eval() | |
| # Create a wrapper to extract features before the final layer | |
| class InceptionFeatureExtractor(torch.nn.Module): | |
| def __init__(self, inception_model): | |
| super().__init__() | |
| self.inception = inception_model | |
| # Remove the final fc layer | |
| self.inception.fc = torch.nn.Identity() | |
| def forward(self, x): | |
| # Pass through all layers except fc | |
| x = self.inception.Conv2d_1a_3x3(x) | |
| x = self.inception.Conv2d_2a_3x3(x) | |
| x = self.inception.Conv2d_2b_3x3(x) | |
| x = self.inception.maxpool1(x) | |
| x = self.inception.Conv2d_3b_1x1(x) | |
| x = self.inception.Conv2d_4a_3x3(x) | |
| x = self.inception.maxpool2(x) | |
| x = self.inception.Mixed_5b(x) | |
| x = self.inception.Mixed_5c(x) | |
| x = self.inception.Mixed_5d(x) | |
| x = self.inception.Mixed_6a(x) | |
| x = self.inception.Mixed_6b(x) | |
| x = self.inception.Mixed_6c(x) | |
| x = self.inception.Mixed_6d(x) | |
| x = self.inception.Mixed_6e(x) | |
| x = self.inception.Mixed_7a(x) | |
| x = self.inception.Mixed_7b(x) | |
| x = self.inception.Mixed_7c(x) | |
| x = self.inception.avgpool(x) | |
| x = torch.flatten(x, 1) | |
| return x | |
| self.model = InceptionFeatureExtractor(inception) | |
| self.model = self.model.to(self.device) | |
| self.model.eval() | |
| # Image preprocessing for InceptionV3 | |
| self.transform = transforms.Compose([ | |
| transforms.Resize((299, 299)), | |
| transforms.ToTensor(), | |
| transforms.Normalize( | |
| mean=[0.485, 0.456, 0.406], | |
| std=[0.229, 0.224, 0.225] | |
| ) | |
| ]) | |
| def get_inception_features(self, image_path): | |
| """Extract InceptionV3 features from an image.""" | |
| image = Image.open(image_path).convert('RGB') | |
| image_tensor = self.transform(image).unsqueeze(0).to(self.device) | |
| with torch.no_grad(): | |
| # Pass through the model up to the average pool | |
| features = self.model(image_tensor) | |
| # Flatten to 1D vector for each image | |
| features = features.view(features.size(0), -1) | |
| return features.cpu().numpy() | |
| def calculate_frechet_distance(self, mu1, sigma1, mu2, sigma2, eps=1e-6): | |
| """Calculate Fréchet distance between two Gaussians.""" | |
| mu1 = np.atleast_1d(mu1) | |
| mu2 = np.atleast_1d(mu2) | |
| sigma1 = np.atleast_2d(sigma1) | |
| sigma2 = np.atleast_2d(sigma2) | |
| assert mu1.shape == mu2.shape, "Statistics must have matching dimensions" | |
| assert sigma1.shape == sigma2.shape, "Statistics must have matching dimensions" | |
| # Compute difference | |
| diff = mu1 - mu2 | |
| # Compute matrix square root | |
| covmean, _ = linalg.sqrtm(sigma1.dot(sigma2), disp=False) | |
| # Handle complex results | |
| if np.iscomplexobj(covmean): | |
| covmean = covmean.real | |
| # Calculate FID | |
| tr_covmean = np.trace(covmean) | |
| fid = diff.dot(diff) + np.trace(sigma1) + np.trace(sigma2) - 2 * tr_covmean | |
| return np.sqrt(np.maximum(fid, 0.0)) | |
| def compute_fid_matrix(self, folder_path): | |
| """ | |
| Compute FID between all pairs of images in a folder. | |
| Lower FID indicates higher similarity. | |
| Args: | |
| folder_path: Path to folder containing images | |
| Returns: | |
| image_files, fid_matrix | |
| """ | |
| # Get all image files | |
| image_extensions = {'.jpg', '.jpeg', '.png', '.bmp', '.gif'} | |
| image_files = sorted([ | |
| f for f in os.listdir(folder_path) | |
| if os.path.splitext(f)[1].lower() in image_extensions | |
| ]) | |
| if not image_files: | |
| print("No images found in the folder!") | |
| return None | |
| print(f"Found {len(image_files)} images: {image_files}") | |
| # Extract features for all images | |
| all_features = {} | |
| print("\nExtracting InceptionV3 features...") | |
| for img_file in image_files: | |
| img_path = os.path.join(folder_path, img_file) | |
| features = self.get_inception_features(img_path) | |
| all_features[img_file] = features | |
| print(f" ✓ {img_file}") | |
| # Compute FID matrix | |
| n_images = len(image_files) | |
| fid_matrix = np.zeros((n_images, n_images)) | |
| print("\nComputing FID-based distances...") | |
| # For single images, we compute a simplified FID using the feature vectors themselves | |
| # Stack all features for covariance computation | |
| all_stacked = np.vstack([all_features[f] for f in image_files]) | |
| for i in range(n_images): | |
| for j in range(n_images): | |
| if i == j: | |
| fid_matrix[i, j] = 0.0 | |
| else: | |
| # Get individual feature vectors | |
| mu1 = all_features[image_files[i]].flatten() | |
| mu2 = all_features[image_files[j]].flatten() | |
| # Use a simplified FID: just compute the Wasserstein distance between features | |
| # with a small regularization for covariance | |
| diff = mu1 - mu2 | |
| # Compute Euclidean distance as FID approximation | |
| fid = np.linalg.norm(diff) | |
| fid_matrix[i, j] = fid | |
| return image_files, fid_matrix | |
| def plot_fid_matrix(self, image_files, fid_matrix, save_path=None): | |
| """Visualize the FID matrix as a heatmap.""" | |
| fig, ax = plt.subplots(figsize=(12, 10)) | |
| sns.heatmap( | |
| fid_matrix, | |
| annot=True, | |
| fmt='.2f', | |
| ax=ax, | |
| cmap='RdYlGn_r', # Reversed: red = high distance (different), green = low distance (similar) | |
| cbar_kws={'label': 'FID Distance (lower = more similar)'} | |
| ) | |
| def add_image_anchors(axis_type, tick_positions, labels): | |
| for i, (pos, img_name) in enumerate(zip(tick_positions, labels)): | |
| # Load and thumbnail the image | |
| img_path = os.path.join('input', img_name) | |
| img = Image.open(img_path).convert('RGB') | |
| img.thumbnail((200, 200)) # Resize for the axis | |
| imagebox = OffsetImage(img, zoom=0.5) # Adjust zoom based on your DPI | |
| if axis_type == 'x': | |
| # Position image below the X-axis | |
| ab = AnnotationBbox(imagebox, (pos, 0), | |
| xybox=(0, -65), # Distance from axis | |
| xycoords=('data', 'axes fraction'), | |
| boxcoords="offset points", | |
| frameon=False) | |
| else: | |
| # Position image to the left of the Y-axis | |
| ab = AnnotationBbox(imagebox, (0, pos), | |
| xybox=(-65, 0), | |
| xycoords=('axes fraction', 'data'), | |
| boxcoords="offset points", | |
| frameon=False) | |
| ax.add_artist(ab) | |
| # Get tick positions (Seaborn centers them at 0.5, 1.5, etc.) | |
| tick_positions = np.arange(len(image_files)) + 0.5 | |
| # Add images to both axes | |
| add_image_anchors('x', tick_positions, image_files) | |
| add_image_anchors('y', tick_positions, image_files) | |
| # Remove text labels to avoid clutter | |
| ax.set_xticklabels([]) | |
| ax.set_yticklabels([]) | |
| plt.title('Fréchet Inception Distance (FID) Matrix') | |
| plt.tight_layout() | |
| if save_path: | |
| # Create directory if it doesn't exist | |
| os.makedirs(os.path.dirname(save_path), exist_ok=True) | |
| plt.savefig(save_path, dpi=150, bbox_inches='tight') | |
| print(f"\nHeatmap saved to {save_path}") | |
| plt.show() | |
| def print_fid_results(self, image_files, fid_matrix): | |
| """Print FID results in a readable format.""" | |
| print("\n" + "="*80) | |
| print("FRÉCHET INCEPTION DISTANCE (FID) RESULTS") | |
| print("="*80) | |
| print("\nNote: Lower FID = more similar images\n") | |
| # Create sorted list of pairwise distances | |
| distances = [] | |
| for i in range(len(image_files)): | |
| for j in range(i + 1, len(image_files)): | |
| distances.append(( | |
| image_files[i], | |
| image_files[j], | |
| fid_matrix[i, j] | |
| )) | |
| # Sort by FID distance | |
| distances.sort(key=lambda x: x[2]) | |
| print("Pairwise FID Distances (sorted by similarity):") | |
| for img1, img2, fid in distances: | |
| # Create a visual representation (inverted: shorter bar = more similar) | |
| max_fid = max(d[2] for d in distances) | |
| bar_length = int((1 - fid / max_fid) * 40) | |
| bar = '█' * bar_length + '░' * (40 - bar_length) | |
| print(f"{img1} <-> {img2}") | |
| print(f" [{bar}] FID: {fid:.4f}") | |
| def main(): | |
| # Set folder path | |
| folder_path = "./input" | |
| print("\n" + "="*80) | |
| print("IMAGE SIMILARITY ANALYSIS") | |
| print("="*80) | |
| print("\nChoose analysis method:") | |
| print("1. ResNet50 + Cosine Similarity (faster, lightweight)") | |
| print("2. InceptionV3 + Fréchet Inception Distance / FID (more robust)") | |
| print("3. Both analyses") | |
| choice = input("\nEnter your choice (1-3): ").strip() | |
| # Method 1: ResNet50 + Cosine Similarity | |
| if choice in ['1', '3']: | |
| print("\n" + "="*80) | |
| print("METHOD 1: ResNet50 + Cosine Similarity") | |
| print("="*80) | |
| similarity_finder = ImageSimilarityFinder(model_name='resnet50') | |
| results = similarity_finder.find_similar_images( | |
| folder_path, | |
| metric='cosine' | |
| ) | |
| if results: | |
| image_files, similarity_matrix = results | |
| similarity_finder.print_similarity_results(image_files, similarity_matrix) | |
| output_path = os.path.join(folder_path,'output', 'similarity_heatmap_resnet50.png') | |
| similarity_finder.plot_similarity_matrix(image_files, similarity_matrix, output_path) | |
| # Method 2: InceptionV3 + FID | |
| if choice in ['2', '3']: | |
| print("\n" + "="*80) | |
| print("METHOD 2: InceptionV3 + Fréchet Inception Distance (FID)") | |
| print("="*80) | |
| fid_finder = FIDSimilarityFinder() | |
| results = fid_finder.compute_fid_matrix(folder_path) | |
| if results: | |
| image_files, fid_matrix = results | |
| fid_finder.print_fid_results(image_files, fid_matrix) | |
| output_path = os.path.join('./output', 'similarity_heatmap_fid.png') | |
| fid_finder.plot_fid_matrix(image_files, fid_matrix, output_path) | |
| print("\n" + "="*80) | |
| print("✓ Analysis complete!") | |
| print("="*80) | |
| if __name__ == "__main__": | |
| main() | |