File size: 24,829 Bytes
9869d0d | 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 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 | 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()
|