File size: 25,282 Bytes
9a85a36 | 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 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 | import json
import random
import os
from pathlib import Path
import torch
from PIL import Image
import numpy as np
import torchvision.transforms as transforms
from scipy import linalg
import scipy
import torch.nn.functional as F
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
import pickle
import warnings
warnings.filterwarnings('ignore')
from metric import *
"""
Image Quality Evaluation with Caching
This module provides functions to evaluate FID (Fréchet Inception Distance) and
IS (Inception Score) for generated images. It includes intelligent caching to
save computation time on repeated evaluations.
Cache Structure:
- output_dir/eval_cache/
├── real_features.npy # Cached real image features for FID
├── real_features_hash.txt # Hash of real image directory
├── 1k_features.npy # Cached features for 1K images
├── 1k_predictions.npy # Cached predictions for 1K images
├── 1k_folder_hash.txt # Hash of 1K image folder
├── 2k_features.npy # Cached features for 2K images
├── 2k_predictions.npy # Cached predictions for 2K images
├── 2k_folder_hash.txt # Hash of 2K image folder
├── 4k_features.npy # Cached features for 4K images
├── 4k_predictions.npy # Cached predictions for 4K images
└── 4k_folder_hash.txt # Hash of 4K image folder
The cache automatically detects changes in image folders and only recomputes
features when necessary, significantly speeding up repeated evaluations.
"""
def process_json_file(json_file_path, global_path, output_dir="output"):
"""
Read a JSON file, sample 1000 lines, and save text and image paths separately.
Args:
json_file_path (str): Path to the input JSON file
global_path (str): Global path to prepend to image_path
output_dir (str): Directory to save output files
"""
# Create output directory if it doesn't exist
Path(output_dir).mkdir(parents=True, exist_ok=True)
# Read the JSON file
print(f"Reading JSON file: {json_file_path}")
with open(json_file_path, 'r', encoding='utf-8') as f:
data = json.load(f)
# Convert to list if it's not already
if not isinstance(data, list):
data = [data]
# Sample 1000 lines (or all if less than 1000)
sample_size = min(1000, len(data))
sampled_data = random.sample(data, sample_size)
print(f"Sampled {sample_size} lines from {len(data)} total lines")
su
# Process the data
image_paths = []
texts = []
for item in sampled_data:
# Extract fields
image_path = item.get('image_path', '')
text = item.get('text', '')
# Combine image_path with global path
image_link = os.path.join(global_path, image_path) if image_path else ''
image_paths.append(image_link)
texts.append(text)
# Save text samples
text_file = os.path.join(output_dir, 'texts.txt')
with open(text_file, 'w', encoding='utf-8') as f:
for text in texts:
f.write(text + '\n')
# Save image paths
image_file = os.path.join(output_dir, 'image_paths.txt')
with open(image_file, 'w', encoding='utf-8') as f:
for path in image_paths:
f.write(path + '\n')
print(f"Text samples saved to: {text_file}")
print(f"Image paths saved to: {image_file}")
print(f"Total processed items: {len(texts)}")
def clean_fid_resize(output_size=(299, 299)):
s1, s2 = output_size
def resize_single_channel(x_np):
img = Image.fromarray(x_np.astype(np.float32), mode='F')
img = img.resize(output_size, resample=Image.Resampling.BICUBIC)
return np.asarray(img).clip(0, 255).reshape(s2, s1, 1)
def func(x):
x = [resize_single_channel(x[:, :, idx]) for idx in range(3)]
# x = np.concatenate(x, axis=2).astype(np.float32)
x = np.concatenate(x, axis=2).astype(np.uint8)
return x
return func
class ImageDataset(Dataset):
"""Dataset for loading images from a directory."""
def __init__(self, image_dir, transform=None, use_clean_fid=False):
self.image_dir = image_dir
self.image_files = [f for f in os.listdir(image_dir) if f.lower().endswith(('.png', '.jpg', '.jpeg'))]
self.image_files.sort()
if use_clean_fid:
self.transform = transforms.ToTensor()
self.resize_fn = clean_fid_resize(output_size=(299, 299))
else:
self.transform = transforms.Compose([
transforms.Resize((299, 299)),
transforms.ToTensor(),
])
self.use_clean_fid = use_clean_fid
def __len__(self):
return len(self.image_files)
def __getitem__(self, idx):
img_path = os.path.join(self.image_dir, self.image_files[idx])
image = Image.open(img_path).convert('RGB')
if self.use_clean_fid:
image_np = np.array(image)
image_np = self.resize_fn(image_np)
image = self.transform(image_np)
else:
image = self.transform(image)
return image
class ImagePatchDataset(Dataset):
"""Dataset for loading images from a directory.
For each image, we will return 10 random patches (1024x1024)"""
def __init__(self, image_dir, num_patches=10):
self.image_dir = image_dir
self.image_files = [f for f in os.listdir(image_dir) if f.lower().endswith(('.png', '.jpg', '.jpeg'))]
self.image_files.sort()
self.num_patches = num_patches
self.transform = transforms.Compose([
transforms.RandomCrop((1024, 1024)),
transforms.Resize((299, 299)),
transforms.ToTensor(),
])
def __len__(self):
return len(self.image_files)
def __getitem__(self, idx):
img_path = os.path.join(self.image_dir, self.image_files[idx])
image = Image.open(img_path).convert('RGB')
output = []
for _ in range(self.num_patches):
output.append(self.transform(image))
image = torch.stack(output)
return image
class ImagePathDataset(Dataset):
"""Dataset for loading images from a list of file paths."""
def __init__(self, image_paths, use_clean_fid=False):
self.image_paths = image_paths
if use_clean_fid:
self.transform = transforms.ToTensor()
self.resize_fn = clean_fid_resize(output_size=(299, 299))
else:
self.transform = transforms.Compose([
transforms.Resize((299, 299)),
transforms.ToTensor(),
])
self.use_clean_fid = use_clean_fid
def __len__(self):
return len(self.image_paths)
def __getitem__(self, idx):
img_path = self.image_paths[idx]
try:
image = Image.open(img_path).convert('RGB')
if self.use_clean_fid:
image_np = np.array(image)
image_np = self.resize_fn(image_np)
image = self.transform(image_np)
else:
image = self.transform(image)
return image
except Exception as e:
print(f"Error loading image {img_path}: {str(e)}")
# Return a black image as fallback
if self.transform:
return self.transform(Image.new('RGB', (299, 299), (0, 0, 0)))
return Image.new('RGB', (299, 299), (0, 0, 0))
def get_folder_hash(folder_path):
"""
Generate a hash of folder contents to detect changes.
Args:
folder_path (str): Path to the folder
Returns:
str: MD5 hash of folder contents
"""
import hashlib
import os
hash_md5 = hashlib.md5()
# Get all image files in the folder
image_files = []
for file in os.listdir(folder_path):
if file.lower().endswith(('.png', '.jpg', '.jpeg')):
image_files.append(file)
# Sort files for consistent hashing
image_files.sort()
# Hash the list of files and their modification times
for file in image_files:
file_path = os.path.join(folder_path, file)
# Include filename and modification time in hash
file_info = f"{file}:{os.path.getmtime(file_path)}"
hash_md5.update(file_info.encode())
return hash_md5.hexdigest()
def clear_evaluation_cache(output_dir):
"""
Clear the evaluation cache for a given output directory.
Args:
output_dir (str): Directory containing the cache to clear
"""
cache_dir = os.path.join(output_dir, 'eval_cache')
if os.path.exists(cache_dir):
import shutil
shutil.rmtree(cache_dir)
print(f"Cleared evaluation cache: {cache_dir}")
else:
print(f"No cache found at: {cache_dir}")
def check_cache_status(output_dir):
"""
Check the status of evaluation cache for a given output directory.
Args:
output_dir (str): Directory containing the cache to check
"""
cache_dir = os.path.join(output_dir, 'eval_cache')
if not os.path.exists(cache_dir):
print(f"No cache directory found at: {cache_dir}")
return
print(f"Cache directory: {cache_dir}")
print("Cache contents:")
# List all cache files
cache_files = [f for f in os.listdir(cache_dir) if f.endswith('.npy')]
hash_files = [f for f in os.listdir(cache_dir) if f.endswith('.txt')]
if cache_files:
print("\nFeature files:")
for file in sorted(cache_files):
file_path = os.path.join(cache_dir, file)
size_mb = os.path.getsize(file_path) / (1024 * 1024)
print(f" {file}: {size_mb:.1f} MB")
if hash_files:
print("\nHash files:")
for file in sorted(hash_files):
print(f" {file}")
# Check for chunked cache
chunk_files = [f for f in cache_files if 'chunk_' in f]
if chunk_files:
print(f"\nChunked processing detected: {len(chunk_files)} chunk files")
chunk_prefixes = set([f.split('_chunk_')[0] for f in chunk_files])
for prefix in chunk_prefixes:
prefix_chunks = [f for f in chunk_files if f.startswith(prefix)]
print(f" {prefix}: {len(prefix_chunks)} chunks")
def create_image_paths_file(image_dir, output_file, file_extensions=('.png', '.jpg', '.jpeg')):
"""
Create a text file containing paths to all images in a directory.
Args:
image_dir (str): Directory containing images
output_file (str): Path to output text file
file_extensions (tuple): File extensions to include
"""
if not os.path.exists(image_dir):
print(f"Error: Directory '{image_dir}' does not exist!")
return
image_paths = []
for root, dirs, files in os.walk(image_dir):
for file in files:
if file.lower().endswith(file_extensions):
full_path = os.path.join(root, file)
image_paths.append(full_path)
# Sort paths for consistency
image_paths.sort()
# Write to file
with open(output_file, 'w', encoding='utf-8') as f:
for path in image_paths:
f.write(path + '\n')
print(f"Created image paths file: {output_file}")
print(f"Total images found: {len(image_paths)}")
def evaluate_image_quality(
existing_folders,
real_image_dir=None,
batch_size=32,
device='cuda',
use_cache=True,
chunk_size=5000,
use_patch=False,
real_cache_dir: str = None
):
"""
Evaluate FID and IS scores for generated images in 1K, 2K, and 4K folders.
Args:
output_dir (str): Directory containing the generated images
real_image_dir (str): Directory containing real images for FID comparison, or text file containing image paths
batch_size (int): Batch size for processing
device (str): Device to use for computation
use_cache (bool): Whether to use cached features if available
chunk_size (int): Number of samples per chunk for large datasets
Returns:
Dictionary containing evaluation results
"""
print("Starting image quality evaluation...")
print_memory_usage("Start of evaluation")
output_dir, _ = os.path.split(existing_folders[0])
# Create cache directory
cache_dir = real_cache_dir
if cache_dir is not None:
assert os.path.exists(cache_dir), f"Cache directory {cache_dir} does not exist"
gen_cache_dir = os.path.join(output_dir, 'eval_cache')
os.makedirs(gen_cache_dir, exist_ok=True)
# Initialize models
fid_model = InceptionFeatureExtractor(return_features="fid")
is_model = InceptionFeatureExtractor(return_features="is")
fid_model.to(device)
is_model.to(device)
results = {}
# Load or extract real image features for FID
real_features = None
if real_image_dir and os.path.exists(real_image_dir):
real_features_cache_path = os.path.join(cache_dir, 'real_features.npy')
real_features_hash_path = os.path.join(cache_dir, 'real_features_hash.txt')
if use_cache and os.path.exists(real_features_cache_path):
print("Loading cached real image features...")
real_features = np.load(real_features_cache_path)
print(f"Loaded {len(real_features)} real image features from cache")
else:
print(f"Extracting real image features using chunked processing...")
# Check if real_image_dir is a text file or directory
if real_image_dir.endswith('.txt'):
print(f"Reading image paths from text file: {real_image_dir}")
# Read image paths from text file
with open(real_image_dir, 'r', encoding='utf-8') as f:
image_paths = [line.strip() for line in f.readlines() if line.strip()]
print(f"Found {len(image_paths)} image paths in text file")
# Create dataset from image paths
real_dataset = ImagePathDataset(image_paths)
else:
# Create dataset for real images from directory
real_dataset = ImageDataset(real_image_dir)
total_images = len(real_dataset)
print(f"Found {total_images} real images in directory")
if total_images > 50000:
indices = torch.randperm(total_images)[:50000]
real_dataset = torch.utils.data.Subset(real_dataset, indices)
print(f"Subsampled to {len(indices)} images for evaluation")
# Use chunked processing for large datasets
if len(real_dataset) > chunk_size:
print(f"Large dataset detected ({len(real_dataset)} images). Using chunked processing with chunk size {chunk_size}.")
real_features = extract_features_chunked(
model=fid_model,
dataset=real_dataset,
device=device,
batch_size=batch_size,
chunk_size=chunk_size,
cache_dir=cache_dir,
cache_prefix="real"
)
else:
# For smaller datasets, use regular processing
real_dataloader = DataLoader(real_dataset, batch_size=batch_size, shuffle=False, num_workers=2)
real_features = extract_features(fid_model, real_dataloader, device)
# Save features to cache
np.save(real_features_cache_path, real_features)
# Save hash of real image directory and chunk size for cache validation
import hashlib
cache_info = f"{real_image_dir}\n{chunk_size}\n{len(real_features)}"
real_dir_hash = hashlib.md5(cache_info.encode()).hexdigest()
with open(real_features_hash_path, 'w') as f:
f.write(cache_info + f"\n{real_dir_hash}")
print(f"Saved {len(real_features)} real image features to cache")
# Evaluate each resolution folder
list_resolution = []
for folder_path in existing_folders:
_, current_name = os.path.splitext(folder_path)
resolution = current_name.split('_')[-1]
list_resolution.append(resolution)
print(f"\nEvaluating {resolution} images...")
# HARD-CODE to alway recompute Cache paths for this resolution
gen_features_cache_path = os.path.join(gen_cache_dir, f'{resolution}_features.npy')
predictions_cache_path = os.path.join(gen_cache_dir, f'{resolution}_predictions.npy')
folder_hash_path = os.path.join(gen_cache_dir, f'{resolution}_folder_hash.txt')
# Load generated images
try:
if use_patch:
gen_dataset = ImagePatchDataset(folder_path)
collate_fn = lambda batch: torch.cat(batch, dim=0)
else:
# Sample only 731 images from the dataset
# import random
_full_dataset = ImageDataset(folder_path)
gen_dataset = _full_dataset
# total_images = len(_full_dataset)
# sample_size = min(731, total_images)
# if sample_size < total_images:
# indices = sorted(random.sample(range(total_images), sample_size))
# gen_dataset = torch.utils.data.Subset(_full_dataset, indices)
# else:
# gen_dataset = _full_dataset
collate_fn = None
gen_dataloader = DataLoader(gen_dataset, batch_size=batch_size, shuffle=False, num_workers=2, collate_fn=collate_fn)
# Check if we can use cached features
use_cached_features = False
if use_cache and os.path.exists(gen_features_cache_path) and os.path.exists(predictions_cache_path):
# Check if folder content has changed
current_hash = get_folder_hash(folder_path)
cached_hash = None
if os.path.exists(folder_hash_path):
with open(folder_hash_path, 'r') as f:
cached_hash = f.read().strip()
if current_hash == cached_hash:
use_cached_features = True
print(f"Using cached features for {resolution}...")
if use_cached_features:
# Load cached features and predictions
gen_features = np.load(gen_features_cache_path)
predictions = np.load(predictions_cache_path)
print(f"Loaded {len(gen_features)} features and {len(predictions)} predictions from cache")
else:
# Extract features and predictions
print(f"Extracting features for {resolution}...")
# Use chunked processing for large generated datasets
if len(gen_dataset) > chunk_size:
print(f"Large generated dataset detected ({len(gen_dataset)} images). Using chunked processing.")
gen_features = extract_features_chunked(
model=fid_model,
dataset=gen_dataset,
device=device,
batch_size=batch_size,
chunk_size=chunk_size,
cache_dir=gen_cache_dir,
cache_prefix=f"{resolution}_fid"
)
else:
gen_features = extract_features(fid_model, gen_dataloader, device)
print(f"Getting predictions for {resolution}...")
# Use chunked processing for predictions too
if len(gen_dataset) > chunk_size:
predictions = extract_features_chunked(
model=is_model,
dataset=gen_dataset,
device=device,
batch_size=batch_size,
chunk_size=chunk_size,
cache_dir=gen_cache_dir,
cache_prefix=f"{resolution}_is"
)
# Convert features to predictions (for IS model, features are predictions)
predictions = F.softmax(torch.from_numpy(predictions), dim=1).numpy()
else:
predictions = get_predictions(is_model, gen_dataloader, device)
# Save to cache
# np.save(gen_features_cache_path, gen_features)
# np.save(predictions_cache_path, predictions)
# # Save folder hash
# current_hash = get_folder_hash(folder_path)
# with open(folder_hash_path, 'w') as f:
# f.write(current_hash)
# print(f"Saved {len(gen_features)} features and {len(predictions)} predictions to cache")
# Calculate Inception Score
print(f"Calculating Inception Score for {resolution}...")
is_mean, is_std = calculate_inception_score(predictions)
results[f"{resolution}_IS"] = {
'mean': float(is_mean),
'std': float(is_std)
}
print(f"{resolution} Inception Score: {is_mean:.4f} ± {is_std:.4f}")
# Calculate FID if real images are provided
if real_features is not None:
print(f"Calculating FID for {resolution}...")
fid_score = calculate_fid(real_features, gen_features)
results[f"{resolution}_FID"] = float(fid_score)
print(f"{resolution} FID Score: {fid_score:.4f}")
else:
print(f"Skipping FID calculation for {resolution} (no real images provided)")
results[f"{resolution}_FID"] = None
except Exception as e:
print(f"Error evaluating {resolution}: {str(e)}")
results[f"{resolution}_IS"] = {'mean': None, 'std': None}
results[f"{resolution}_FID"] = None
# Save results
results_file = os.path.join(output_dir, 'evaluation_results.json')
with open(results_file, 'w') as f:
json.dump(results, f, indent=2)
print(f"\nEvaluation results saved to: {results_file}")
# Print summary
print("\n" + "="*50)
print("EVALUATION SUMMARY")
print("="*50)
for resolution in list_resolution:
if f"{resolution}_IS" in results:
is_result = results[f"{resolution}_IS"]
if is_result['mean'] is not None:
print(f"{resolution.upper()}:")
print(f" Inception Score: {is_result['mean']:.4f} ± {is_result['std']:.4f}")
if results[f"{resolution}_FID"] is not None:
print(f" FID Score: {results[f'{resolution}_FID']:.4f}")
print()
return results
def run_evaluation_only(
output_dir,
real_image_dir=None,
batch_size=32,
device='cuda',
use_cache=True,
chunk_size=5000,
use_patch=False,
real_cache_dir: str = None
):
"""
Standalone function to run evaluation only (without image generation).
Args:
output_dir (str): Directory containing the generated images
real_image_dir (str): Directory containing real images for FID comparison
batch_size (int): Batch size for processing
device (str): Device to use for computation
use_cache (bool): Whether to use cached features if available
chunk_size (int): Number of samples per chunk for large datasets
"""
print("Running image quality evaluation only...")
if not os.path.exists(output_dir):
print(f"Error: Output directory '{output_dir}' does not exist!")
return
# Check if any of the image folders exist
image_folders = []
for prefix in ['image', 'img']:
for suffix in ['1k', '2k', '4k', '1024', '2048', '4096']:
image_folders.append(os.path.join(output_dir, f"{prefix}_{suffix}"))
existing_folders = [f for f in image_folders if os.path.exists(f)]
if not existing_folders:
print(f"Error: No image folders found in '{output_dir}'!")
print(f"Expected folders: {image_folders}")
return
print(f"Found image folders: {[os.path.basename(f) for f in existing_folders]}")
# Run evaluation
results = evaluate_image_quality(
existing_folders=existing_folders,
real_image_dir=real_image_dir,
batch_size=batch_size,
device=device,
use_cache=use_cache,
chunk_size=chunk_size,
use_patch=use_patch,
real_cache_dir=real_cache_dir
)
return results
|