Download experiments/image2image/image_similarity.py from jacodd/SynthField: direct link, hf CLI and curl.
- Browser
- Download file 24.8 kB
-
https://huggingface.co/datasets/jacodd/SynthField/resolve/main/experiments/image2image/image_similarity.py
- Command line
-
hf download hf://datasets/jacodd/SynthField/experiments/image2image/image_similarity.py
-
curl -L -o image_similarity.py https://huggingface.co/datasets/jacodd/SynthField/resolve/main/experiments/image2image/image_similarity.py
24.8 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 | |
| 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', target_image_file=None): | |
| """ | |
| Find similarities between images in a folder. | |
| If target_image_file is specified, computes similarity of all other images to that one. | |
| Otherwise, computes an all-vs-all similarity matrix. | |
| Args: | |
| folder_path: Path to folder containing images | |
| metric: 'cosine' or 'euclidean' | |
| target_image_file: Filename of the image to compare against others. | |
| Returns: | |
| If target_image_file is given: (other_image_files, similarity_scores_1d) | |
| If target_image_file is None: (all_image_files, similarity_matrix_2d) | |
| """ | |
| # 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}") | |
| if target_image_file: | |
| if target_image_file not in embeddings: | |
| print(f"Error: Target image '{target_image_file}' not found in folder.") | |
| return None | |
| print(f"\nComputing similarity of '{target_image_file}' against other images...") | |
| target_embedding = embeddings[target_image_file] | |
| other_files = [f for f in image_files if f != target_image_file] | |
| scores = [] | |
| for other_file in other_files: | |
| score = self.compute_similarity(target_embedding, embeddings[other_file], metric=metric) | |
| scores.append(score) | |
| return other_files, np.array(scores) | |
| else: | |
| # 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, folder_path=None, target_image_file=None): | |
| """Visualize the similarity matrix as a heatmap, or as a bar chart if a target image is provided.""" | |
| if target_image_file and folder_path and similarity_matrix.ndim == 1: | |
| # One-vs-all bar chart | |
| from matplotlib.offsetbox import OffsetImage, AnnotationBbox | |
| plt.figure(figsize=(15, 9)) | |
| ax = plt.gca() | |
| # Sort for better visualization | |
| sorted_indices = np.argsort(similarity_matrix)[::-1] | |
| sorted_files = [image_files[i] for i in sorted_indices] | |
| sorted_scores = similarity_matrix[sorted_indices] | |
| ax.bar(range(len(sorted_files)), sorted_scores, color='lightblue') | |
| ax.set_xticks(range(len(sorted_files))) | |
| ax.set_xticklabels([]) # Hide text labels, we will use images | |
| for i, filename in enumerate(sorted_files): | |
| try: | |
| img_path = os.path.join(folder_path, filename) | |
| img = Image.open(img_path).convert("RGB") | |
| img.thumbnail((120, 120)) # Resize for label | |
| oi = OffsetImage(img, zoom=0.7) | |
| box = AnnotationBbox(oi, (i, 0), frameon=False, xybox=(0, -50), boxcoords="data", pad=0, xycoords="data", box_alignment=(0.5, 1.0)) | |
| ax.add_artist(box) | |
| # Add score text above bar | |
| ax.text(i, sorted_scores[i] + 0.01, f'{sorted_scores[i]:.3f}', ha='center', va='bottom', fontsize=9) | |
| except FileNotFoundError: | |
| print(f"Warning: could not find image {filename} to create label.") | |
| ax.text(i, -0.1, filename, rotation=90, ha='center', va='top') | |
| ax.set_ylim(0, 1.1) | |
| ax.set_xlim(-0.7, len(image_files) - 0.3) | |
| ax.set_ylabel('Cosine Similarity (higher = more similar)') | |
| ax.set_title(f'Similarity of other images compared to "{target_image_file}"') | |
| plt.tight_layout(rect=[0, 0.1, 1, 0.95]) # Adjust layout to make space for images | |
| else: | |
| # Original heatmap for matrix | |
| 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"\nPlot saved to {save_path}") | |
| plt.show() | |
| def print_similarity_results(self, image_files, similarity_matrix, target_image_file=None): | |
| """Print similarity results in a readable format.""" | |
| print("\n" + "="*80) | |
| print("IMAGE SIMILARITY RESULTS") | |
| print("="*80 + "\n") | |
| if target_image_file and similarity_matrix.ndim == 1: | |
| print(f"Similarities compared to '{target_image_file}':\n") | |
| # Sort for printing | |
| sorted_pairs = sorted(zip(similarity_matrix, image_files), reverse=True) | |
| for similarity, img_file in sorted_pairs: | |
| bar_length = int(similarity * 40) | |
| bar = '█' * bar_length + '░' * (40 - bar_length) | |
| print(f"{img_file}") | |
| print(f" [{bar}] {similarity:.4f}") | |
| else: | |
| 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, target_image_file=None): | |
| """ | |
| Compute FID between all pairs of images in a folder, or against a single target image. | |
| Lower FID indicates higher similarity. | |
| Args: | |
| folder_path: Path to folder containing images | |
| target_image_file: If specified, compute FID of other images against this one. | |
| Returns: | |
| image_files, fid_scores (1D or 2D array) | |
| """ | |
| # 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}") | |
| if target_image_file: | |
| if target_image_file not in all_features: | |
| print(f"Error: Target image '{target_image_file}' not found.") | |
| return None | |
| print(f"\nComputing FID of '{target_image_file}' against other images...") | |
| target_mu = all_features[target_image_file].flatten() | |
| other_files = [f for f in image_files if f != target_image_file] | |
| fid_scores = [] | |
| for other_file in other_files: | |
| other_mu = all_features[other_file].flatten() | |
| fid = np.linalg.norm(other_mu - target_mu) | |
| fid_scores.append(fid) | |
| return other_files, np.array(fid_scores) | |
| else: | |
| # Compute FID matrix | |
| n_images = len(image_files) | |
| fid_matrix = np.zeros((n_images, n_images)) | |
| print("\nComputing FID-based distances...") | |
| for i in range(n_images): | |
| for j in range(i, n_images): | |
| if i == j: | |
| fid_matrix[i, j] = 0.0 | |
| else: | |
| mu1 = all_features[image_files[i]].flatten() | |
| mu2 = all_features[image_files[j]].flatten() | |
| # Compute Euclidean distance as FID approximation | |
| fid = np.linalg.norm(mu1 - mu2) | |
| fid_matrix[i, j] = fid | |
| fid_matrix[j, i] = fid | |
| return image_files, fid_matrix | |
| def plot_fid_matrix(self, image_files, fid_matrix, save_path=None, folder_path=None, target_image_file=None): | |
| """Visualize the FID matrix as a heatmap, or as a bar chart if a target image is provided.""" | |
| if target_image_file and folder_path and fid_matrix.ndim == 1: | |
| # One-vs-all bar chart for FID | |
| from matplotlib.offsetbox import OffsetImage, AnnotationBbox | |
| plt.figure(figsize=(15, 9)) | |
| ax = plt.gca() | |
| # Sort by distance (ascending) | |
| sorted_indices = np.argsort(fid_matrix) | |
| sorted_files = [image_files[i] for i in sorted_indices] | |
| sorted_scores = fid_matrix[sorted_indices] | |
| ax.bar(range(len(sorted_files)), sorted_scores, color='lightgreen') | |
| ax.set_xticks(range(len(sorted_files))) | |
| ax.set_xticklabels([]) | |
| for i, filename in enumerate(sorted_files): | |
| try: | |
| img_path = os.path.join(folder_path, filename) | |
| img = Image.open(img_path).convert("RGB") | |
| img.thumbnail((120, 120)) | |
| oi = OffsetImage(img, zoom=0.7) | |
| box = AnnotationBbox(oi, (i, 0), frameon=False, xybox=(0, -50), boxcoords="data", pad=0, xycoords="data", box_alignment=(0.5, 1.0)) | |
| ax.add_artist(box) | |
| ax.text(i, sorted_scores[i], f'{sorted_scores[i]:.2f}', ha='center', va='bottom', fontsize=9, bbox=dict(facecolor='white', alpha=0.5, pad=1)) | |
| except FileNotFoundError: | |
| print(f"Warning: could not find image {filename} to create label.") | |
| ax.text(i, -0.1, filename, rotation=90, ha='center', va='top') | |
| if len(sorted_scores) > 0: | |
| ax.set_ylim(0, max(sorted_scores) * 1.15) | |
| ax.set_xlim(-0.7, len(image_files) - 0.3) | |
| ax.set_ylabel('FID Distance (lower = more similar)') | |
| ax.set_title(f'FID Distance of other images from "{target_image_file}"') | |
| plt.tight_layout(rect=[0, 0.1, 1, 0.95]) | |
| else: | |
| # Original heatmap | |
| plt.figure(figsize=(10, 8)) | |
| sns.heatmap( | |
| fid_matrix, | |
| xticklabels=image_files, | |
| yticklabels=image_files, | |
| annot=True, | |
| fmt='.2f', | |
| cmap='RdYlGn_r', # Reversed: red = high distance (different), green = low distance (similar) | |
| cbar_kws={'label': 'FID Distance (lower = more similar)'} | |
| ) | |
| 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, target_image_file=None): | |
| """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") | |
| if target_image_file and fid_matrix.ndim == 1: | |
| print(f"FID distances from '{target_image_file}':\n") | |
| # Sort for printing | |
| sorted_pairs = sorted(zip(fid_matrix, image_files)) | |
| if not sorted_pairs: return | |
| max_fid = sorted_pairs[-1][0] if sorted_pairs else 1 | |
| for fid, img_file in sorted_pairs: | |
| # Inverted bar: shorter is better | |
| bar_length = int((1 - fid / max_fid) * 40) if max_fid > 0 else 0 | |
| bar = '█' * bar_length + '░' * (40 - bar_length) | |
| print(f"{img_file}") | |
| print(f" [{bar}] FID: {fid:.4f}") | |
| else: | |
| # 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]) | |
| if not distances: return | |
| print("Pairwise FID Distances (sorted by similarity):") | |
| max_fid = max(d[2] for d in distances) if distances else 1 | |
| for img1, img2, fid in distances: | |
| # Create a visual representation (inverted: shorter bar = more similar) | |
| bar_length = int((1 - fid / max_fid) * 40) if max_fid > 0 else 0 | |
| bar = '█' * bar_length + '░' * (40 - bar_length) | |
| print(f"{img1} <-> {img2}") | |
| print(f" [{bar}] FID: {fid:.4f}") | |
| def main(): | |
| # Set folder path and target image | |
| folder_path = "./input" | |
| target_image_file = "rosario.jpg" # The image to compare against others | |
| # Check if target file exists | |
| if not os.path.exists(os.path.join(folder_path, target_image_file)): | |
| print(f"Error: Target image '{target_image_file}' not found in '{folder_path}'") | |
| # List other available images | |
| try: | |
| image_extensions = {'.jpg', '.jpeg', '.png', '.bmp', '.gif'} | |
| avail_images = [f for f in os.listdir(folder_path) if os.path.splitext(f)[1].lower() in image_extensions] | |
| if avail_images: | |
| print("Available images:", avail_images) | |
| except FileNotFoundError: | |
| print(f"Error: Folder '{folder_path}' not found.") | |
| return | |
| print("\n" + "="*80) | |
| print("IMAGE SIMILARITY ANALYSIS") | |
| print(f"Target Image: {target_image_file}") | |
| print("="*80) | |
| # Always perform both analyses for the target image | |
| # Method 1: ResNet50 + Cosine Similarity | |
| 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', | |
| target_image_file=target_image_file | |
| ) | |
| if results: | |
| image_files, similarity_scores = results | |
| similarity_finder.print_similarity_results(image_files, similarity_scores, target_image_file=target_image_file) | |
| output_path = os.path.join(folder_path,'output', f'similarity_to_{Path(target_image_file).stem}_resnet50.png') | |
| similarity_finder.plot_similarity_matrix(image_files, similarity_scores, output_path, folder_path=folder_path, target_image_file=target_image_file) | |
| # Method 2: InceptionV3 + FID | |
| 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, target_image_file=target_image_file) | |
| if results: | |
| image_files, fid_scores = results | |
| fid_finder.print_fid_results(image_files, fid_scores, target_image_file=target_image_file) | |
| output_path = os.path.join(folder_path,'output', f'similarity_to_{Path(target_image_file).stem}_fid.png') | |
| fid_finder.plot_fid_matrix(image_files, fid_scores, output_path, folder_path=folder_path, target_image_file=target_image_file) | |
| print("\n" + "="*80) | |
| print("✓ Analysis complete!") | |
| print("="*80) | |
| if __name__ == "__main__": | |
| main() | |