complete the project with additional analyze metric, create comparisons. Update requirements.txt
Browse files- .gitignore +2 -0
- analyze_metrics.py +577 -0
- create_comparison.py +127 -0
- requirements.txt +19 -0
- test.py +277 -0
.gitignore
CHANGED
|
@@ -2,3 +2,5 @@
|
|
| 2 |
.DS_Store
|
| 3 |
cifar_data/
|
| 4 |
__pycache__/
|
|
|
|
|
|
|
|
|
| 2 |
.DS_Store
|
| 3 |
cifar_data/
|
| 4 |
__pycache__/
|
| 5 |
+
|
| 6 |
+
output/
|
analyze_metrics.py
ADDED
|
@@ -0,0 +1,577 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Parameter behavior analysis for mosaic generator
|
| 4 |
+
Focuses on: parameter degradation effects, CIFAR comparison, cross-image consistency
|
| 5 |
+
Analyzes three images: akaza, IMG_5090, IMG_6914
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import json
|
| 9 |
+
import pandas as pd
|
| 10 |
+
import numpy as np
|
| 11 |
+
import matplotlib.pyplot as plt
|
| 12 |
+
import seaborn as sns
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
import re
|
| 15 |
+
from collections import defaultdict
|
| 16 |
+
import warnings
|
| 17 |
+
warnings.filterwarnings('ignore')
|
| 18 |
+
|
| 19 |
+
# Configuration
|
| 20 |
+
METRICS_DIR = Path('./output/test_result/metrics')
|
| 21 |
+
OUTPUT_DIR = Path('./output/analysis')
|
| 22 |
+
TARGET_IMAGES = ['akaza', 'IMG_3378', 'IMG_5090', 'IMG_6914']
|
| 23 |
+
|
| 24 |
+
# Visualization settings
|
| 25 |
+
plt.style.use('default')
|
| 26 |
+
sns.set_palette("husl")
|
| 27 |
+
|
| 28 |
+
def setup_directories():
|
| 29 |
+
"""Create analysis output directories"""
|
| 30 |
+
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
|
| 31 |
+
for image in TARGET_IMAGES:
|
| 32 |
+
(OUTPUT_DIR / image).mkdir(parents=True, exist_ok=True)
|
| 33 |
+
print(f"[INFO] Created analysis directories under {OUTPUT_DIR}")
|
| 34 |
+
|
| 35 |
+
def parse_filename(filename):
|
| 36 |
+
"""Parse filename to extract parameters"""
|
| 37 |
+
# Pattern: {image}-min{min}-max{max}-sub{sub}-quant{quant}-{tile}_metrics.json
|
| 38 |
+
pattern = r'(.+)-min(\d+)-max(\d+)-sub([0-9p]+)-quant(\d+)-(.+)_metrics\.json'
|
| 39 |
+
match = re.match(pattern, filename)
|
| 40 |
+
|
| 41 |
+
if not match:
|
| 42 |
+
return None
|
| 43 |
+
|
| 44 |
+
image, min_size, max_size, sub_threshold, quantization, tile_library = match.groups()
|
| 45 |
+
|
| 46 |
+
# Convert threshold back from string (0p1 -> 0.1)
|
| 47 |
+
sub_threshold = sub_threshold.replace('p', '.')
|
| 48 |
+
|
| 49 |
+
return {
|
| 50 |
+
'image': image,
|
| 51 |
+
'min_size': int(min_size),
|
| 52 |
+
'max_size': int(max_size),
|
| 53 |
+
'sub_threshold': float(sub_threshold),
|
| 54 |
+
'quantization': int(quantization),
|
| 55 |
+
'tile_library': tile_library
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
def load_metrics_data():
|
| 59 |
+
"""Load all metrics data and organize by image"""
|
| 60 |
+
data_by_image = defaultdict(list)
|
| 61 |
+
|
| 62 |
+
print("[INFO] Loading metrics data...")
|
| 63 |
+
|
| 64 |
+
for json_file in METRICS_DIR.glob('*.json'):
|
| 65 |
+
# Skip files not belonging to our target images
|
| 66 |
+
if not any(img in json_file.name for img in TARGET_IMAGES):
|
| 67 |
+
continue
|
| 68 |
+
|
| 69 |
+
parsed = parse_filename(json_file.name)
|
| 70 |
+
if parsed is None:
|
| 71 |
+
continue
|
| 72 |
+
|
| 73 |
+
# Load metrics
|
| 74 |
+
try:
|
| 75 |
+
with open(json_file, 'r') as f:
|
| 76 |
+
metrics = json.load(f)
|
| 77 |
+
|
| 78 |
+
# Combine parameters and metrics
|
| 79 |
+
record = {**parsed, **metrics}
|
| 80 |
+
data_by_image[parsed['image']].append(record)
|
| 81 |
+
|
| 82 |
+
except Exception as e:
|
| 83 |
+
print(f"[WARNING] Failed to load {json_file.name}: {e}")
|
| 84 |
+
|
| 85 |
+
# Convert to DataFrames
|
| 86 |
+
dfs = {}
|
| 87 |
+
for image, records in data_by_image.items():
|
| 88 |
+
df = pd.DataFrame(records)
|
| 89 |
+
dfs[image] = df
|
| 90 |
+
print(f"[INFO] Loaded {len(df)} records for {image}")
|
| 91 |
+
|
| 92 |
+
return dfs
|
| 93 |
+
|
| 94 |
+
def create_heatmaps(df, image_name):
|
| 95 |
+
"""Create heatmap visualizations for an image"""
|
| 96 |
+
print(f"[INFO] Creating heatmaps for {image_name}")
|
| 97 |
+
|
| 98 |
+
fig, axes = plt.subplots(2, 2, figsize=(16, 12))
|
| 99 |
+
fig.suptitle(f'Parameter Impact Heatmaps - {image_name}', fontsize=16, fontweight='bold')
|
| 100 |
+
|
| 101 |
+
# 1. Min_size vs Max_size colored by SSIM
|
| 102 |
+
pivot1 = df.pivot_table(values='SSIM', index='min_size', columns='max_size', aggfunc='mean')
|
| 103 |
+
sns.heatmap(pivot1, annot=True, fmt='.3f', ax=axes[0,0], cmap='RdYlGn')
|
| 104 |
+
axes[0,0].set_title('SSIM by Min/Max Size')
|
| 105 |
+
axes[0,0].set_xlabel('Max Size')
|
| 106 |
+
axes[0,0].set_ylabel('Min Size')
|
| 107 |
+
|
| 108 |
+
# 2. Quantization vs Tile_library colored by Overall_Quality
|
| 109 |
+
pivot2 = df.pivot_table(values='Overall_Quality', index='quantization', columns='tile_library', aggfunc='mean')
|
| 110 |
+
sns.heatmap(pivot2, annot=True, fmt='.3f', ax=axes[0,1], cmap='RdYlGn')
|
| 111 |
+
axes[0,1].set_title('Overall Quality by Quantization/Tile Library')
|
| 112 |
+
axes[0,1].set_xlabel('Tile Library')
|
| 113 |
+
axes[0,1].set_ylabel('Quantization')
|
| 114 |
+
|
| 115 |
+
# 3. Subdivision vs Quantization colored by MSE (inverted colormap since lower MSE is better)
|
| 116 |
+
pivot3 = df.pivot_table(values='MSE', index='sub_threshold', columns='quantization', aggfunc='mean')
|
| 117 |
+
sns.heatmap(pivot3, annot=True, fmt='.0f', ax=axes[1,0], cmap='RdYlGn_r')
|
| 118 |
+
axes[1,0].set_title('MSE by Subdivision/Quantization')
|
| 119 |
+
axes[1,0].set_xlabel('Quantization')
|
| 120 |
+
axes[1,0].set_ylabel('Subdivision Threshold')
|
| 121 |
+
|
| 122 |
+
# 4. Tile library vs Min_size colored by Edge_Similarity
|
| 123 |
+
pivot4 = df.pivot_table(values='Edge_Similarity', index='tile_library', columns='min_size', aggfunc='mean')
|
| 124 |
+
sns.heatmap(pivot4, annot=True, fmt='.3f', ax=axes[1,1], cmap='RdYlGn')
|
| 125 |
+
axes[1,1].set_title('Edge Similarity by Tile Library/Min Size')
|
| 126 |
+
axes[1,1].set_xlabel('Min Size')
|
| 127 |
+
axes[1,1].set_ylabel('Tile Library')
|
| 128 |
+
|
| 129 |
+
plt.tight_layout()
|
| 130 |
+
output_path = OUTPUT_DIR / image_name / 'heatmaps.png'
|
| 131 |
+
plt.savefig(output_path, dpi=300, bbox_inches='tight')
|
| 132 |
+
plt.close()
|
| 133 |
+
print(f"[INFO] Saved heatmaps to {output_path}")
|
| 134 |
+
|
| 135 |
+
def create_metric_comparisons(df, image_name):
|
| 136 |
+
"""Create metric comparison charts"""
|
| 137 |
+
print(f"[INFO] Creating metric comparisons for {image_name}")
|
| 138 |
+
|
| 139 |
+
fig, axes = plt.subplots(2, 2, figsize=(16, 12))
|
| 140 |
+
fig.suptitle(f'Metric Comparisons - {image_name}', fontsize=16, fontweight='bold')
|
| 141 |
+
|
| 142 |
+
# 1. Box plots by tile library
|
| 143 |
+
metrics_to_plot = ['SSIM', 'Histogram_Correlation', 'Edge_Similarity', 'Overall_Quality']
|
| 144 |
+
|
| 145 |
+
for i, metric in enumerate(metrics_to_plot):
|
| 146 |
+
ax = axes[i//2, i%2]
|
| 147 |
+
df.boxplot(column=metric, by='tile_library', ax=ax)
|
| 148 |
+
ax.set_title(f'{metric} by Tile Library')
|
| 149 |
+
ax.set_xlabel('Tile Library')
|
| 150 |
+
ax.set_ylabel(metric)
|
| 151 |
+
ax.grid(True, alpha=0.3)
|
| 152 |
+
|
| 153 |
+
plt.suptitle('') # Remove automatic title
|
| 154 |
+
fig.suptitle(f'Metric Distribution by Tile Library - {image_name}', fontsize=16, fontweight='bold')
|
| 155 |
+
plt.tight_layout()
|
| 156 |
+
|
| 157 |
+
output_path = OUTPUT_DIR / image_name / 'metric_comparison.png'
|
| 158 |
+
plt.savefig(output_path, dpi=300, bbox_inches='tight')
|
| 159 |
+
plt.close()
|
| 160 |
+
print(f"[INFO] Saved metric comparison to {output_path}")
|
| 161 |
+
|
| 162 |
+
def create_parameter_impact(df, image_name):
|
| 163 |
+
"""Create parameter impact analysis"""
|
| 164 |
+
print(f"[INFO] Creating parameter impact analysis for {image_name}")
|
| 165 |
+
|
| 166 |
+
fig, axes = plt.subplots(2, 3, figsize=(18, 12))
|
| 167 |
+
fig.suptitle(f'Parameter Impact Analysis - {image_name}', fontsize=16, fontweight='bold')
|
| 168 |
+
|
| 169 |
+
# 1a. Quality metrics by quantization
|
| 170 |
+
quantization_impact = df.groupby('quantization')[['MSE', 'SSIM', 'Histogram_Correlation', 'Edge_Similarity']].mean()
|
| 171 |
+
|
| 172 |
+
quality_metrics = ['SSIM', 'Histogram_Correlation', 'Edge_Similarity']
|
| 173 |
+
quantization_impact[quality_metrics].plot(kind='bar', ax=axes[0,0])
|
| 174 |
+
axes[0,0].set_title('Quality Metrics by Quantization')
|
| 175 |
+
axes[0,0].set_xlabel('Quantization')
|
| 176 |
+
axes[0,0].set_ylabel('Metric Value')
|
| 177 |
+
axes[0,0].legend()
|
| 178 |
+
axes[0,0].tick_params(axis='x', rotation=0)
|
| 179 |
+
axes[0,0].grid(True, alpha=0.3)
|
| 180 |
+
|
| 181 |
+
# 1b. MSE by quantization (separate subplot)
|
| 182 |
+
quantization_impact['MSE'].plot(kind='bar', ax=axes[0,1], color='red')
|
| 183 |
+
axes[0,1].set_title('MSE by Quantization')
|
| 184 |
+
axes[0,1].set_xlabel('Quantization')
|
| 185 |
+
axes[0,1].set_ylabel('MSE')
|
| 186 |
+
axes[0,1].tick_params(axis='x', rotation=0)
|
| 187 |
+
axes[0,1].grid(True, alpha=0.3)
|
| 188 |
+
|
| 189 |
+
# 2. Size ratio impact (max/min)
|
| 190 |
+
df['size_ratio'] = df['max_size'] / df['min_size']
|
| 191 |
+
size_ratio_impact = df.groupby('size_ratio')['Overall_Quality'].mean()
|
| 192 |
+
size_ratio_impact.plot(kind='bar', ax=axes[0,2], color='skyblue')
|
| 193 |
+
axes[0,2].set_title('Overall Quality by Size Ratio (Max/Min)')
|
| 194 |
+
axes[0,2].set_xlabel('Size Ratio')
|
| 195 |
+
axes[0,2].set_ylabel('Overall Quality')
|
| 196 |
+
axes[0,2].tick_params(axis='x', rotation=45)
|
| 197 |
+
axes[0,2].grid(True, alpha=0.3)
|
| 198 |
+
|
| 199 |
+
# 3. Subdivision threshold impact
|
| 200 |
+
sub_impact = df.groupby('sub_threshold')['Overall_Quality'].mean()
|
| 201 |
+
sub_impact.plot(kind='bar', ax=axes[1,0], color='lightcoral')
|
| 202 |
+
axes[1,0].set_title('Overall Quality by Subdivision Threshold')
|
| 203 |
+
axes[1,0].set_xlabel('Subdivision Threshold')
|
| 204 |
+
axes[1,0].set_ylabel('Overall Quality')
|
| 205 |
+
axes[1,0].tick_params(axis='x', rotation=0)
|
| 206 |
+
axes[1,0].grid(True, alpha=0.3)
|
| 207 |
+
|
| 208 |
+
# 4a. Quality metrics by tile library
|
| 209 |
+
tile_performance = df.groupby('tile_library')[['MSE', 'SSIM', 'Histogram_Correlation', 'Edge_Similarity']].mean()
|
| 210 |
+
quality_metrics = ['SSIM', 'Histogram_Correlation', 'Edge_Similarity']
|
| 211 |
+
tile_performance[quality_metrics].plot(kind='bar', ax=axes[1,1])
|
| 212 |
+
axes[1,1].set_title('Quality Metrics by Tile Library')
|
| 213 |
+
axes[1,1].set_xlabel('Tile Library')
|
| 214 |
+
axes[1,1].set_ylabel('Metric Value')
|
| 215 |
+
axes[1,1].legend()
|
| 216 |
+
axes[1,1].tick_params(axis='x', rotation=45)
|
| 217 |
+
axes[1,1].grid(True, alpha=0.3)
|
| 218 |
+
|
| 219 |
+
# 4b. MSE by tile library
|
| 220 |
+
tile_performance['MSE'].plot(kind='bar', ax=axes[1,2], color='red')
|
| 221 |
+
axes[1,2].set_title('MSE by Tile Library')
|
| 222 |
+
axes[1,2].set_xlabel('Tile Library')
|
| 223 |
+
axes[1,2].set_ylabel('MSE')
|
| 224 |
+
axes[1,2].tick_params(axis='x', rotation=45)
|
| 225 |
+
axes[1,2].grid(True, alpha=0.3)
|
| 226 |
+
|
| 227 |
+
plt.tight_layout()
|
| 228 |
+
output_path = OUTPUT_DIR / image_name / 'parameter_impact.png'
|
| 229 |
+
plt.savefig(output_path, dpi=300, bbox_inches='tight')
|
| 230 |
+
plt.close()
|
| 231 |
+
print(f"[INFO] Saved parameter impact to {output_path}")
|
| 232 |
+
|
| 233 |
+
def analyze_parameter_degradation(df, image_name):
|
| 234 |
+
"""Analyze which parameters cause quality degradation (for artistic/mosaic effects)"""
|
| 235 |
+
print(f"[INFO] Analyzing parameter degradation effects for {image_name}")
|
| 236 |
+
|
| 237 |
+
fig, axes = plt.subplots(2, 2, figsize=(16, 12))
|
| 238 |
+
fig.suptitle(f'Parameter Degradation Analysis (For Artistic Effects) - {image_name}', fontsize=16, fontweight='bold')
|
| 239 |
+
|
| 240 |
+
# 1. Which parameters INCREASE MSE (worse quality = more artistic)
|
| 241 |
+
mse_by_param = {}
|
| 242 |
+
mse_by_param['quantization'] = df.groupby('quantization')['MSE'].mean()
|
| 243 |
+
mse_by_param['min_size'] = df.groupby('min_size')['MSE'].mean()
|
| 244 |
+
mse_by_param['max_size'] = df.groupby('max_size')['MSE'].mean()
|
| 245 |
+
mse_by_param['sub_threshold'] = df.groupby('sub_threshold')['MSE'].mean()
|
| 246 |
+
|
| 247 |
+
# Plot MSE increase trends
|
| 248 |
+
ax = axes[0,0]
|
| 249 |
+
colors = ['red', 'orange', 'green', 'blue']
|
| 250 |
+
for i, (param, values) in enumerate(mse_by_param.items()):
|
| 251 |
+
ax.plot(values.index, values.values, marker='o', label=param, color=colors[i], linewidth=2)
|
| 252 |
+
|
| 253 |
+
ax.set_title('MSE by Parameters (Higher = More Artistic)')
|
| 254 |
+
ax.set_xlabel('Parameter Value')
|
| 255 |
+
ax.set_ylabel('Average MSE')
|
| 256 |
+
ax.legend()
|
| 257 |
+
ax.grid(True, alpha=0.3)
|
| 258 |
+
|
| 259 |
+
# 2. Which parameters DECREASE SSIM (worse similarity = more artistic)
|
| 260 |
+
ssim_by_param = {}
|
| 261 |
+
ssim_by_param['quantization'] = df.groupby('quantization')['SSIM'].mean()
|
| 262 |
+
ssim_by_param['min_size'] = df.groupby('min_size')['SSIM'].mean()
|
| 263 |
+
ssim_by_param['max_size'] = df.groupby('max_size')['SSIM'].mean()
|
| 264 |
+
ssim_by_param['sub_threshold'] = df.groupby('sub_threshold')['SSIM'].mean()
|
| 265 |
+
|
| 266 |
+
ax = axes[0,1]
|
| 267 |
+
for i, (param, values) in enumerate(ssim_by_param.items()):
|
| 268 |
+
ax.plot(values.index, values.values, marker='s', label=param, color=colors[i], linewidth=2)
|
| 269 |
+
|
| 270 |
+
ax.set_title('SSIM by Parameters (Lower = More Artistic)')
|
| 271 |
+
ax.set_xlabel('Parameter Value')
|
| 272 |
+
ax.set_ylabel('Average SSIM')
|
| 273 |
+
ax.legend()
|
| 274 |
+
ax.grid(True, alpha=0.3)
|
| 275 |
+
|
| 276 |
+
# 3. Parameter impact ranking for degradation
|
| 277 |
+
degradation_impact = {}
|
| 278 |
+
|
| 279 |
+
# Calculate impact as difference between max and min values (normalized)
|
| 280 |
+
for param in ['quantization', 'min_size', 'max_size', 'sub_threshold']:
|
| 281 |
+
mse_range = mse_by_param[param].max() - mse_by_param[param].min()
|
| 282 |
+
ssim_range = ssim_by_param[param].max() - ssim_by_param[param].min()
|
| 283 |
+
|
| 284 |
+
# Normalize by overall metric range
|
| 285 |
+
mse_impact = mse_range / df['MSE'].std()
|
| 286 |
+
ssim_impact = ssim_range / df['SSIM'].std()
|
| 287 |
+
|
| 288 |
+
degradation_impact[param] = (mse_impact + ssim_impact) / 2
|
| 289 |
+
|
| 290 |
+
# Plot simple impact ranking
|
| 291 |
+
ax = axes[1,0]
|
| 292 |
+
params = list(degradation_impact.keys())
|
| 293 |
+
impacts = list(degradation_impact.values())
|
| 294 |
+
|
| 295 |
+
ax.bar(params, impacts, color='lightcoral')
|
| 296 |
+
ax.set_title('Parameter Impact on Quality Degradation')
|
| 297 |
+
ax.set_xlabel('Parameters')
|
| 298 |
+
ax.set_ylabel('Impact Score')
|
| 299 |
+
ax.tick_params(axis='x', rotation=45)
|
| 300 |
+
ax.grid(True, alpha=0.3)
|
| 301 |
+
|
| 302 |
+
# Add score labels
|
| 303 |
+
for i, (param, impact) in enumerate(zip(params, impacts)):
|
| 304 |
+
ax.text(i, impact + 0.05, f'{impact:.2f}', ha='center', va='bottom')
|
| 305 |
+
|
| 306 |
+
# 4. Empty subplot (remove recommendations)
|
| 307 |
+
axes[1,1].axis('off')
|
| 308 |
+
|
| 309 |
+
plt.tight_layout()
|
| 310 |
+
output_path = OUTPUT_DIR / image_name / 'parameter_degradation.png'
|
| 311 |
+
plt.savefig(output_path, dpi=300, bbox_inches='tight')
|
| 312 |
+
plt.close()
|
| 313 |
+
print(f"[INFO] Saved parameter degradation analysis to {output_path}")
|
| 314 |
+
|
| 315 |
+
def analyze_cifar_comparison(df, image_name):
|
| 316 |
+
"""Direct comparison between CIFAR-10 and CIFAR-100"""
|
| 317 |
+
print(f"[INFO] Analyzing CIFAR-10 vs CIFAR-100 comparison for {image_name}")
|
| 318 |
+
|
| 319 |
+
# Filter data for CIFAR comparisons only
|
| 320 |
+
cifar_data = df[df['tile_library'].isin(['cifar-10', 'cifar-100'])].copy()
|
| 321 |
+
|
| 322 |
+
if len(cifar_data) == 0:
|
| 323 |
+
print(f"[WARNING] No CIFAR data found for {image_name}")
|
| 324 |
+
return
|
| 325 |
+
|
| 326 |
+
fig, axes = plt.subplots(2, 2, figsize=(16, 12))
|
| 327 |
+
fig.suptitle(f'CIFAR-10 vs CIFAR-100 Direct Comparison - {image_name}', fontsize=16, fontweight='bold')
|
| 328 |
+
|
| 329 |
+
# 1a. Quality metrics comparison
|
| 330 |
+
metrics = ['MSE', 'SSIM', 'Histogram_Correlation', 'Edge_Similarity']
|
| 331 |
+
cifar_comparison = cifar_data.groupby('tile_library')[metrics].mean()
|
| 332 |
+
|
| 333 |
+
quality_metrics = ['SSIM', 'Histogram_Correlation', 'Edge_Similarity']
|
| 334 |
+
cifar_comparison[quality_metrics].T.plot(kind='bar', ax=axes[0,0], color=['lightblue', 'lightcoral'])
|
| 335 |
+
axes[0,0].set_title('Quality Metrics Comparison')
|
| 336 |
+
axes[0,0].set_ylabel('Metric Value')
|
| 337 |
+
axes[0,0].legend(title='Tile Library')
|
| 338 |
+
axes[0,0].tick_params(axis='x', rotation=45)
|
| 339 |
+
axes[0,0].grid(True, alpha=0.3)
|
| 340 |
+
|
| 341 |
+
# 1b. MSE comparison (separate subplot)
|
| 342 |
+
cifar_comparison['MSE'].plot(kind='bar', ax=axes[0,1], color=['red', 'orange'])
|
| 343 |
+
axes[0,1].set_title('MSE Comparison')
|
| 344 |
+
axes[0,1].set_ylabel('MSE')
|
| 345 |
+
axes[0,1].legend(['CIFAR-10', 'CIFAR-100'])
|
| 346 |
+
axes[0,1].grid(True, alpha=0.3)
|
| 347 |
+
|
| 348 |
+
# 2. Paired comparison for same parameter settings
|
| 349 |
+
# Create parameter combination identifier
|
| 350 |
+
cifar_data['param_combo'] = (cifar_data['min_size'].astype(str) + '_' +
|
| 351 |
+
cifar_data['max_size'].astype(str) + '_' +
|
| 352 |
+
cifar_data['sub_threshold'].astype(str) + '_' +
|
| 353 |
+
cifar_data['quantization'].astype(str))
|
| 354 |
+
|
| 355 |
+
# Find configurations that exist for both CIFAR types
|
| 356 |
+
cifar10_combos = set(cifar_data[cifar_data['tile_library'] == 'cifar-10']['param_combo'])
|
| 357 |
+
cifar100_combos = set(cifar_data[cifar_data['tile_library'] == 'cifar-100']['param_combo'])
|
| 358 |
+
common_combos = cifar10_combos.intersection(cifar100_combos)
|
| 359 |
+
|
| 360 |
+
paired_data = []
|
| 361 |
+
for combo in common_combos:
|
| 362 |
+
combo_data = cifar_data[cifar_data['param_combo'] == combo]
|
| 363 |
+
if len(combo_data) == 2: # Should have both CIFAR-10 and CIFAR-100
|
| 364 |
+
cifar10_row = combo_data[combo_data['tile_library'] == 'cifar-10'].iloc[0]
|
| 365 |
+
cifar100_row = combo_data[combo_data['tile_library'] == 'cifar-100'].iloc[0]
|
| 366 |
+
|
| 367 |
+
paired_data.append({
|
| 368 |
+
'combo': combo,
|
| 369 |
+
'cifar10_ssim': cifar10_row['SSIM'],
|
| 370 |
+
'cifar100_ssim': cifar100_row['SSIM'],
|
| 371 |
+
'cifar10_mse': cifar10_row['MSE'],
|
| 372 |
+
'cifar100_mse': cifar100_row['MSE'],
|
| 373 |
+
'ssim_diff': cifar10_row['SSIM'] - cifar100_row['SSIM'],
|
| 374 |
+
'mse_diff': cifar10_row['MSE'] - cifar100_row['MSE']
|
| 375 |
+
})
|
| 376 |
+
|
| 377 |
+
paired_df = pd.DataFrame(paired_data)
|
| 378 |
+
|
| 379 |
+
# 2. Win/Loss analysis
|
| 380 |
+
ax = axes[1,0]
|
| 381 |
+
if len(paired_df) > 0:
|
| 382 |
+
ssim_wins = (paired_df['ssim_diff'] > 0).sum() # CIFAR-10 wins
|
| 383 |
+
ssim_losses = (paired_df['ssim_diff'] < 0).sum() # CIFAR-100 wins
|
| 384 |
+
|
| 385 |
+
mse_wins = (paired_df['mse_diff'] < 0).sum() # CIFAR-10 wins (lower MSE is better)
|
| 386 |
+
mse_losses = (paired_df['mse_diff'] > 0).sum() # CIFAR-100 wins
|
| 387 |
+
|
| 388 |
+
categories = ['SSIM', 'MSE']
|
| 389 |
+
cifar10_scores = [ssim_wins, mse_wins]
|
| 390 |
+
cifar100_scores = [ssim_losses, mse_losses]
|
| 391 |
+
|
| 392 |
+
x = np.arange(len(categories))
|
| 393 |
+
width = 0.35
|
| 394 |
+
|
| 395 |
+
ax.bar(x - width/2, cifar10_scores, width, label='CIFAR-10 Wins', color='lightblue')
|
| 396 |
+
ax.bar(x + width/2, cifar100_scores, width, label='CIFAR-100 Wins', color='lightcoral')
|
| 397 |
+
|
| 398 |
+
ax.set_title(f'Win/Loss Analysis ({len(paired_df)} comparisons)')
|
| 399 |
+
ax.set_ylabel('Number of Wins')
|
| 400 |
+
ax.set_xticks(x)
|
| 401 |
+
ax.set_xticklabels(categories)
|
| 402 |
+
ax.legend()
|
| 403 |
+
ax.grid(True, alpha=0.3)
|
| 404 |
+
|
| 405 |
+
# Add value labels
|
| 406 |
+
for i, (c10, c100) in enumerate(zip(cifar10_scores, cifar100_scores)):
|
| 407 |
+
ax.text(i - width/2, c10 + 0.5, str(c10), ha='center', va='bottom')
|
| 408 |
+
ax.text(i + width/2, c100 + 0.5, str(c100), ha='center', va='bottom')
|
| 409 |
+
|
| 410 |
+
# 3. Performance difference distribution
|
| 411 |
+
ax = axes[1,1]
|
| 412 |
+
if len(paired_df) > 0:
|
| 413 |
+
ax.hist(paired_df['ssim_diff'], bins=20, alpha=0.7, color='skyblue', edgecolor='black')
|
| 414 |
+
ax.axvline(x=0, color='red', linestyle='--', linewidth=2)
|
| 415 |
+
ax.set_title('SSIM Difference Distribution (CIFAR-10 - CIFAR-100)')
|
| 416 |
+
ax.set_xlabel('SSIM Difference')
|
| 417 |
+
ax.set_ylabel('Frequency')
|
| 418 |
+
ax.grid(True, alpha=0.3)
|
| 419 |
+
|
| 420 |
+
plt.tight_layout()
|
| 421 |
+
output_path = OUTPUT_DIR / image_name / 'cifar_comparison.png'
|
| 422 |
+
plt.savefig(output_path, dpi=300, bbox_inches='tight')
|
| 423 |
+
plt.close()
|
| 424 |
+
print(f"[INFO] Saved CIFAR comparison to {output_path}")
|
| 425 |
+
|
| 426 |
+
def analyze_size_consistency(all_dfs):
|
| 427 |
+
"""Analyze if min/max size effects are consistent across images"""
|
| 428 |
+
print("[INFO] Analyzing min/max size consistency across images")
|
| 429 |
+
|
| 430 |
+
fig, axes = plt.subplots(2, 2, figsize=(16, 12))
|
| 431 |
+
fig.suptitle('Min/Max Size Effects Consistency Across Images', fontsize=16, fontweight='bold')
|
| 432 |
+
|
| 433 |
+
# Combine all data
|
| 434 |
+
combined_data = []
|
| 435 |
+
for image_name, df in all_dfs.items():
|
| 436 |
+
df_copy = df.copy()
|
| 437 |
+
df_copy['image'] = image_name
|
| 438 |
+
combined_data.append(df_copy)
|
| 439 |
+
|
| 440 |
+
combined_df = pd.concat(combined_data, ignore_index=True)
|
| 441 |
+
|
| 442 |
+
# 1. Min size effect on SSIM across images
|
| 443 |
+
ax = axes[0,0]
|
| 444 |
+
for image in TARGET_IMAGES:
|
| 445 |
+
image_data = combined_df[combined_df['image'] == image]
|
| 446 |
+
min_size_effect = image_data.groupby('min_size')['SSIM'].mean()
|
| 447 |
+
ax.plot(min_size_effect.index, min_size_effect.values, marker='o', label=image, linewidth=2)
|
| 448 |
+
|
| 449 |
+
ax.set_title('Min Size Effect on SSIM')
|
| 450 |
+
ax.set_xlabel('Min Size')
|
| 451 |
+
ax.set_ylabel('Average SSIM')
|
| 452 |
+
ax.legend()
|
| 453 |
+
ax.grid(True, alpha=0.3)
|
| 454 |
+
|
| 455 |
+
# 2. Max size effect on SSIM across images
|
| 456 |
+
ax = axes[0,1]
|
| 457 |
+
for image in TARGET_IMAGES:
|
| 458 |
+
image_data = combined_df[combined_df['image'] == image]
|
| 459 |
+
max_size_effect = image_data.groupby('max_size')['SSIM'].mean()
|
| 460 |
+
ax.plot(max_size_effect.index, max_size_effect.values, marker='s', label=image, linewidth=2)
|
| 461 |
+
|
| 462 |
+
ax.set_title('Max Size Effect on SSIM')
|
| 463 |
+
ax.set_xlabel('Max Size')
|
| 464 |
+
ax.set_ylabel('Average SSIM')
|
| 465 |
+
ax.legend()
|
| 466 |
+
ax.grid(True, alpha=0.3)
|
| 467 |
+
|
| 468 |
+
# 3. Size ratio consistency
|
| 469 |
+
combined_df['size_ratio'] = combined_df['max_size'] / combined_df['min_size']
|
| 470 |
+
|
| 471 |
+
ax = axes[1,0]
|
| 472 |
+
for image in TARGET_IMAGES:
|
| 473 |
+
image_data = combined_df[combined_df['image'] == image]
|
| 474 |
+
ratio_effect = image_data.groupby('size_ratio')['Overall_Quality'].mean()
|
| 475 |
+
ax.plot(ratio_effect.index, ratio_effect.values, marker='^', label=image, linewidth=2)
|
| 476 |
+
|
| 477 |
+
ax.set_title('Size Ratio Effect on Overall Quality')
|
| 478 |
+
ax.set_xlabel('Size Ratio (Max/Min)')
|
| 479 |
+
ax.set_ylabel('Average Overall Quality')
|
| 480 |
+
ax.legend()
|
| 481 |
+
ax.grid(True, alpha=0.3)
|
| 482 |
+
|
| 483 |
+
# 4. Size ratio effect comparison
|
| 484 |
+
ax = axes[1,1]
|
| 485 |
+
|
| 486 |
+
# Show correlation values as a simple bar chart
|
| 487 |
+
consistency_analysis = {}
|
| 488 |
+
|
| 489 |
+
for size_param in ['min_size', 'max_size']:
|
| 490 |
+
param_effects = {}
|
| 491 |
+
for image in TARGET_IMAGES:
|
| 492 |
+
image_data = combined_df[combined_df['image'] == image]
|
| 493 |
+
effect = image_data.groupby(size_param)['SSIM'].mean()
|
| 494 |
+
param_effects[image] = effect
|
| 495 |
+
|
| 496 |
+
# Calculate correlation between images
|
| 497 |
+
correlations = []
|
| 498 |
+
images = list(param_effects.keys())
|
| 499 |
+
for i in range(len(images)):
|
| 500 |
+
for j in range(i+1, len(images)):
|
| 501 |
+
# Find common parameter values
|
| 502 |
+
common_params = set(param_effects[images[i]].index).intersection(
|
| 503 |
+
set(param_effects[images[j]].index)
|
| 504 |
+
)
|
| 505 |
+
if len(common_params) > 1:
|
| 506 |
+
vals_i = [param_effects[images[i]][p] for p in common_params]
|
| 507 |
+
vals_j = [param_effects[images[j]][p] for p in common_params]
|
| 508 |
+
corr = np.corrcoef(vals_i, vals_j)[0,1]
|
| 509 |
+
correlations.append(corr)
|
| 510 |
+
|
| 511 |
+
consistency_analysis[size_param] = np.mean(correlations) if correlations else 0
|
| 512 |
+
|
| 513 |
+
# Plot consistency as bar chart
|
| 514 |
+
params = list(consistency_analysis.keys())
|
| 515 |
+
correlations = list(consistency_analysis.values())
|
| 516 |
+
|
| 517 |
+
ax.bar(params, correlations, color=['skyblue', 'lightgreen'])
|
| 518 |
+
ax.set_title('Parameter Consistency Across Images')
|
| 519 |
+
ax.set_xlabel('Size Parameters')
|
| 520 |
+
ax.set_ylabel('Average Correlation')
|
| 521 |
+
ax.set_ylim(0, 1)
|
| 522 |
+
ax.grid(True, alpha=0.3)
|
| 523 |
+
|
| 524 |
+
# Add correlation values
|
| 525 |
+
for i, (param, corr) in enumerate(zip(params, correlations)):
|
| 526 |
+
ax.text(i, corr + 0.02, f'{corr:.3f}', ha='center', va='bottom')
|
| 527 |
+
|
| 528 |
+
plt.tight_layout()
|
| 529 |
+
output_path = OUTPUT_DIR / 'size_consistency_analysis.png'
|
| 530 |
+
plt.savefig(output_path, dpi=300, bbox_inches='tight')
|
| 531 |
+
plt.close()
|
| 532 |
+
print(f"[INFO] Saved size consistency analysis to {output_path}")
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
def main():
|
| 536 |
+
"""Main analysis function"""
|
| 537 |
+
print("=" * 60)
|
| 538 |
+
print("MOSAIC PARAMETER BEHAVIOR ANALYSIS")
|
| 539 |
+
print("=" * 60)
|
| 540 |
+
|
| 541 |
+
setup_directories()
|
| 542 |
+
|
| 543 |
+
# Load data
|
| 544 |
+
all_dfs = load_metrics_data()
|
| 545 |
+
|
| 546 |
+
if not all_dfs:
|
| 547 |
+
print("[ERROR] No data loaded. Check metrics directory.")
|
| 548 |
+
return
|
| 549 |
+
|
| 550 |
+
# Analyze each image
|
| 551 |
+
for image_name, df in all_dfs.items():
|
| 552 |
+
print(f"\n[INFO] Analyzing {image_name}...")
|
| 553 |
+
|
| 554 |
+
# Keep original heatmaps and parameter impact
|
| 555 |
+
create_heatmaps(df, image_name)
|
| 556 |
+
create_parameter_impact(df, image_name)
|
| 557 |
+
|
| 558 |
+
# New analyses
|
| 559 |
+
analyze_parameter_degradation(df, image_name)
|
| 560 |
+
analyze_cifar_comparison(df, image_name)
|
| 561 |
+
|
| 562 |
+
# Cross-image consistency analysis
|
| 563 |
+
analyze_size_consistency(all_dfs)
|
| 564 |
+
|
| 565 |
+
print("\n" + "=" * 60)
|
| 566 |
+
print("ANALYSIS COMPLETE!")
|
| 567 |
+
print("=" * 60)
|
| 568 |
+
print(f"Results saved to: {OUTPUT_DIR}")
|
| 569 |
+
print("\nGenerated analyses:")
|
| 570 |
+
print("• heatmaps.png - Parameter impact heatmaps")
|
| 571 |
+
print("• parameter_impact.png - Parameter effect analysis")
|
| 572 |
+
print("• parameter_degradation.png - Settings for artistic effects")
|
| 573 |
+
print("• cifar_comparison.png - CIFAR-10 vs CIFAR-100 comparison")
|
| 574 |
+
print("• size_consistency_analysis.png - Cross-image size effect consistency")
|
| 575 |
+
|
| 576 |
+
if __name__ == "__main__":
|
| 577 |
+
main()
|
create_comparison.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Create horizontal comparison of IMG_3378 mosaic images with different min_size settings
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from PIL import Image, ImageDraw, ImageFont
|
| 7 |
+
import os
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
# Image paths for Figure 3 (2x2 grid)
|
| 11 |
+
image_paths = [
|
| 12 |
+
"./samples/akaza.jpg", # Original
|
| 13 |
+
"./output/test_result/mosaic_images/akaza-min16-max32-sub5-quant0-cifar-10.jpg",
|
| 14 |
+
"./output/test_result/mosaic_images/akaza-min16-max32-sub5-quant16-cifar-10.jpg",
|
| 15 |
+
"./output/test_result/mosaic_images/akaza-min16-max32-sub5-quant32-cifar-10.jpg"
|
| 16 |
+
]
|
| 17 |
+
|
| 18 |
+
# Labels for each image
|
| 19 |
+
labels = ["Original", "quant = 0", "quant = 16", "quant = 32"]
|
| 20 |
+
|
| 21 |
+
def create_comparison():
|
| 22 |
+
"""Create 2x2 grid comparison image"""
|
| 23 |
+
|
| 24 |
+
# Load images
|
| 25 |
+
images = []
|
| 26 |
+
for path in image_paths:
|
| 27 |
+
if os.path.exists(path):
|
| 28 |
+
img = Image.open(path).convert('RGB')
|
| 29 |
+
images.append(img)
|
| 30 |
+
print(f"[INFO] Loaded: {path} | size = {img.size}")
|
| 31 |
+
else:
|
| 32 |
+
print(f"[ERROR] File not found: {path}")
|
| 33 |
+
return None
|
| 34 |
+
|
| 35 |
+
if len(images) != 4:
|
| 36 |
+
print(f"[ERROR] Expected 4 images, found {len(images)}")
|
| 37 |
+
return None
|
| 38 |
+
|
| 39 |
+
# Get dimensions and calculate scale
|
| 40 |
+
original_width, original_height = images[0].size
|
| 41 |
+
|
| 42 |
+
# Scale down to fit reasonable comparison size (e.g., each image 400px wide)
|
| 43 |
+
target_width = 400
|
| 44 |
+
scale = target_width / original_width
|
| 45 |
+
target_height = int(original_height * scale)
|
| 46 |
+
|
| 47 |
+
print(f"[INFO] Scaling from {original_width}x{original_height} to {target_width}x{target_height}")
|
| 48 |
+
|
| 49 |
+
# Resize all images to same scale
|
| 50 |
+
resized_images = []
|
| 51 |
+
for img in images:
|
| 52 |
+
resized = img.resize((target_width, target_height), Image.BICUBIC)
|
| 53 |
+
resized_images.append(resized)
|
| 54 |
+
|
| 55 |
+
# Create comparison canvas for 2x2 grid
|
| 56 |
+
margin = 20
|
| 57 |
+
label_height = 40
|
| 58 |
+
canvas_width = target_width * 2 + margin * 3
|
| 59 |
+
canvas_height = target_height * 2 + label_height + margin * 4
|
| 60 |
+
|
| 61 |
+
canvas = Image.new('RGB', (canvas_width, canvas_height), color='white')
|
| 62 |
+
|
| 63 |
+
# Paste images in 2x2 grid
|
| 64 |
+
draw = ImageDraw.Draw(canvas)
|
| 65 |
+
|
| 66 |
+
# Try to use a system font, fallback to default
|
| 67 |
+
try:
|
| 68 |
+
font = ImageFont.truetype("/System/Library/Fonts/Arial.ttf", 20)
|
| 69 |
+
except:
|
| 70 |
+
try:
|
| 71 |
+
font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 20)
|
| 72 |
+
except:
|
| 73 |
+
font = ImageFont.load_default()
|
| 74 |
+
|
| 75 |
+
for i, (img, label) in enumerate(zip(resized_images, labels)):
|
| 76 |
+
# Calculate grid position (2x2)
|
| 77 |
+
row = i // 2
|
| 78 |
+
col = i % 2
|
| 79 |
+
|
| 80 |
+
x_pos = margin + col * (target_width + margin)
|
| 81 |
+
y_pos = margin + label_height + row * (target_height + margin)
|
| 82 |
+
|
| 83 |
+
canvas.paste(img, (x_pos, y_pos))
|
| 84 |
+
|
| 85 |
+
# Add label above each image
|
| 86 |
+
bbox = draw.textbbox((0, 0), label, font=font)
|
| 87 |
+
text_width = bbox[2] - bbox[0]
|
| 88 |
+
text_x = x_pos + (target_width - text_width) // 2
|
| 89 |
+
text_y = y_pos - label_height + 5
|
| 90 |
+
|
| 91 |
+
draw.text((text_x, text_y), label, fill='black', font=font)
|
| 92 |
+
|
| 93 |
+
# Add title
|
| 94 |
+
title = "Figure 3. Akaza Color Quantization Comparison (min16-max32-sub5-cifar-10)"
|
| 95 |
+
try:
|
| 96 |
+
title_font = ImageFont.truetype("/System/Library/Fonts/Arial.ttf", 16)
|
| 97 |
+
except:
|
| 98 |
+
title_font = font
|
| 99 |
+
|
| 100 |
+
title_bbox = draw.textbbox((0, 0), title, font=title_font)
|
| 101 |
+
title_width = title_bbox[2] - title_bbox[0]
|
| 102 |
+
title_x = (canvas_width - title_width) // 2
|
| 103 |
+
title_y = canvas_height - margin + 5
|
| 104 |
+
|
| 105 |
+
draw.text((title_x, title_y), title, fill='gray', font=title_font)
|
| 106 |
+
|
| 107 |
+
return canvas
|
| 108 |
+
|
| 109 |
+
def main():
|
| 110 |
+
print("=" * 60)
|
| 111 |
+
print("Creating Akaza Color Quantization Comparison")
|
| 112 |
+
print("=" * 60)
|
| 113 |
+
|
| 114 |
+
# Create comparison
|
| 115 |
+
comparison_img = create_comparison()
|
| 116 |
+
|
| 117 |
+
if comparison_img:
|
| 118 |
+
# Save result
|
| 119 |
+
output_path = "./output/akaza_quantization_comparison.png"
|
| 120 |
+
comparison_img.save(output_path, quality=95)
|
| 121 |
+
print(f"\n[SUCCESS] Comparison saved to: {output_path}")
|
| 122 |
+
print(f"[INFO] Canvas size: {comparison_img.size}")
|
| 123 |
+
else:
|
| 124 |
+
print("\n[ERROR] Failed to create comparison")
|
| 125 |
+
|
| 126 |
+
if __name__ == "__main__":
|
| 127 |
+
main()
|
requirements.txt
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Core dependencies for Interactive Image Mosaic Generator
|
| 2 |
+
torch>=2.0.0
|
| 3 |
+
torchvision>=0.15.0
|
| 4 |
+
pillow>=9.0.0
|
| 5 |
+
numpy>=1.21.0
|
| 6 |
+
|
| 7 |
+
# GUI framework
|
| 8 |
+
gradio>=4.0.0
|
| 9 |
+
|
| 10 |
+
# Image processing and computer vision
|
| 11 |
+
opencv-python>=4.5.0
|
| 12 |
+
scikit-image>=0.19.0
|
| 13 |
+
|
| 14 |
+
# Data analysis and progress tracking
|
| 15 |
+
pandas>=1.3.0
|
| 16 |
+
tqdm>=4.60.0
|
| 17 |
+
|
| 18 |
+
# Optional: for better performance
|
| 19 |
+
scipy>=1.7.0
|
test.py
ADDED
|
@@ -0,0 +1,277 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Comprehensive test script for Interactive Image Mosaic Generator
|
| 4 |
+
Tests multiple parameter combinations and saves results with performance metrics
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import os
|
| 8 |
+
import json
|
| 9 |
+
import csv
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from itertools import product
|
| 12 |
+
import tempfile
|
| 13 |
+
from tqdm import tqdm
|
| 14 |
+
import pandas as pd
|
| 15 |
+
|
| 16 |
+
from simple_mosaic import SimpleMosaicImage
|
| 17 |
+
from tile_library import build_cifar10_tile_library, build_cifar100_tile_library
|
| 18 |
+
from performance import calculate_all_metrics
|
| 19 |
+
from PIL import Image
|
| 20 |
+
|
| 21 |
+
# Test parameters
|
| 22 |
+
TEST_PARAMS = {
|
| 23 |
+
'min_size': [4, 16, 32],
|
| 24 |
+
'start_size': [32, 64, 128], # max size
|
| 25 |
+
'threshold': [0.1, 5.0], # subdivision threshold
|
| 26 |
+
'color_quantization': [0, 16, 32],
|
| 27 |
+
'tile_library': ['none', 'cifar-10', 'cifar-100']
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
# Input and output directories
|
| 31 |
+
SAMPLES_DIR = Path('./samples')
|
| 32 |
+
OUTPUT_DIR = Path('./output/test_result')
|
| 33 |
+
MOSAIC_DIR = OUTPUT_DIR / 'mosaic_images'
|
| 34 |
+
METRICS_DIR = OUTPUT_DIR / 'metrics'
|
| 35 |
+
|
| 36 |
+
# Tile cache to avoid reloading
|
| 37 |
+
tile_cache = {}
|
| 38 |
+
|
| 39 |
+
def setup_directories():
|
| 40 |
+
"""Create necessary output directories"""
|
| 41 |
+
for dir_path in [OUTPUT_DIR, MOSAIC_DIR, METRICS_DIR]:
|
| 42 |
+
dir_path.mkdir(parents=True, exist_ok=True)
|
| 43 |
+
print(f"[INFO] Created output directories under {OUTPUT_DIR}")
|
| 44 |
+
|
| 45 |
+
def get_tile_library(tile_type, max_per_class=500):
|
| 46 |
+
"""Get cached tile library or create new one"""
|
| 47 |
+
if tile_type == 'none':
|
| 48 |
+
return None, None, None
|
| 49 |
+
|
| 50 |
+
cache_key = f"{tile_type}_{max_per_class}"
|
| 51 |
+
|
| 52 |
+
if cache_key not in tile_cache:
|
| 53 |
+
print(f"[INFO] Loading {tile_type} tile library...")
|
| 54 |
+
if tile_type == "cifar-10":
|
| 55 |
+
tiles, means, labels = build_cifar10_tile_library(max_per_class=max_per_class)
|
| 56 |
+
elif tile_type == "cifar-100":
|
| 57 |
+
tiles, means, labels = build_cifar100_tile_library(max_per_class=max_per_class)
|
| 58 |
+
else:
|
| 59 |
+
return None, None, None
|
| 60 |
+
|
| 61 |
+
tile_cache[cache_key] = (tiles, means, labels)
|
| 62 |
+
print(f"[INFO] Cached {len(tiles)} tiles for {tile_type}")
|
| 63 |
+
|
| 64 |
+
return tile_cache[cache_key]
|
| 65 |
+
|
| 66 |
+
def generate_filename(image_name, min_size, start_size, threshold, color_quantization, tile_library):
|
| 67 |
+
"""Generate standardized filename for results"""
|
| 68 |
+
# Clean image name (remove extension)
|
| 69 |
+
base_name = Path(image_name).stem
|
| 70 |
+
|
| 71 |
+
# Format threshold to avoid decimal issues
|
| 72 |
+
threshold_str = f"{threshold:g}".replace('.', 'p')
|
| 73 |
+
|
| 74 |
+
# Create filename
|
| 75 |
+
filename = f"{base_name}-min{min_size}-max{start_size}-sub{threshold_str}-quant{color_quantization}-{tile_library}"
|
| 76 |
+
|
| 77 |
+
return filename
|
| 78 |
+
|
| 79 |
+
def process_single_combination(image_path, params, progress_bar=None):
|
| 80 |
+
"""Process a single parameter combination and return results"""
|
| 81 |
+
image_name = image_path.name
|
| 82 |
+
min_size, start_size, threshold, color_quantization, tile_library = params
|
| 83 |
+
|
| 84 |
+
try:
|
| 85 |
+
# Load original image
|
| 86 |
+
original_image = Image.open(image_path).convert("RGB")
|
| 87 |
+
|
| 88 |
+
# Create temporary file for processing
|
| 89 |
+
with tempfile.NamedTemporaryFile(suffix='.jpg', delete=False) as tmp_file:
|
| 90 |
+
original_image.save(tmp_file.name)
|
| 91 |
+
|
| 92 |
+
# Load and process image
|
| 93 |
+
loader = SimpleMosaicImage(tmp_file.name)
|
| 94 |
+
|
| 95 |
+
# Apply resize if needed (use existing MAX_IMAGE_SIZE logic)
|
| 96 |
+
MAX_IMAGE_SIZE = 4500
|
| 97 |
+
if max(loader.width, loader.height) > MAX_IMAGE_SIZE:
|
| 98 |
+
loader.resize(MAX_IMAGE_SIZE)
|
| 99 |
+
|
| 100 |
+
# Apply color quantization if requested
|
| 101 |
+
if color_quantization > 0:
|
| 102 |
+
loader.quantize_colors(color_quantization)
|
| 103 |
+
|
| 104 |
+
# Smart boundary handling
|
| 105 |
+
loader.crop_to_grid(2)
|
| 106 |
+
|
| 107 |
+
# Build adaptive cells
|
| 108 |
+
cells = loader.build_adaptive_cells(
|
| 109 |
+
start_size=start_size,
|
| 110 |
+
min_size=min_size,
|
| 111 |
+
threshold=threshold
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
# Generate mosaic based on tile type
|
| 115 |
+
if tile_library == "none":
|
| 116 |
+
result_img = loader.mosaic_average_color_adaptive(cells)
|
| 117 |
+
processing_info = f"Average colors with {len(cells)} adaptive cells"
|
| 118 |
+
else:
|
| 119 |
+
tiles, tile_means, _ = get_tile_library(tile_library, max_per_class=500)
|
| 120 |
+
if tiles is None:
|
| 121 |
+
raise ValueError(f"Failed to load {tile_library} tile library")
|
| 122 |
+
|
| 123 |
+
result_img = loader.mosaic_with_tiles_adaptive(cells, tiles, tile_means)
|
| 124 |
+
processing_info = f"{tile_library} with {len(cells)} cells using {len(tiles)} tiles"
|
| 125 |
+
|
| 126 |
+
# Calculate metrics
|
| 127 |
+
metrics = calculate_all_metrics(original_image, result_img)
|
| 128 |
+
|
| 129 |
+
# Generate filenames
|
| 130 |
+
base_filename = generate_filename(
|
| 131 |
+
image_name, min_size, start_size, threshold, color_quantization, tile_library
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
# Save mosaic image
|
| 135 |
+
mosaic_path = MOSAIC_DIR / f"{base_filename}.jpg"
|
| 136 |
+
result_img.save(mosaic_path, quality=95)
|
| 137 |
+
|
| 138 |
+
# Save metrics
|
| 139 |
+
metrics_path = METRICS_DIR / f"{base_filename}_metrics.json"
|
| 140 |
+
with open(metrics_path, 'w') as f:
|
| 141 |
+
json.dump(metrics, f, indent=2)
|
| 142 |
+
|
| 143 |
+
# Clean up temporary file
|
| 144 |
+
os.unlink(tmp_file.name)
|
| 145 |
+
|
| 146 |
+
# Update progress bar
|
| 147 |
+
if progress_bar:
|
| 148 |
+
progress_bar.set_postfix({
|
| 149 |
+
'image': image_name[:15],
|
| 150 |
+
'params': f"min{min_size}_max{start_size}_sub{threshold:g}_q{color_quantization}_{tile_library[:6]}"
|
| 151 |
+
})
|
| 152 |
+
progress_bar.update(1)
|
| 153 |
+
|
| 154 |
+
return {
|
| 155 |
+
'image_name': image_name,
|
| 156 |
+
'min_size': min_size,
|
| 157 |
+
'start_size': start_size,
|
| 158 |
+
'threshold': threshold,
|
| 159 |
+
'color_quantization': color_quantization,
|
| 160 |
+
'tile_library': tile_library,
|
| 161 |
+
'num_cells': len(cells),
|
| 162 |
+
'processing_info': processing_info,
|
| 163 |
+
'mosaic_path': str(mosaic_path),
|
| 164 |
+
'metrics_path': str(metrics_path),
|
| 165 |
+
'success': True,
|
| 166 |
+
**metrics
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
except Exception as e:
|
| 170 |
+
error_msg = f"Error processing {image_name} with params {params}: {str(e)}"
|
| 171 |
+
print(f"[ERROR] {error_msg}")
|
| 172 |
+
|
| 173 |
+
if progress_bar:
|
| 174 |
+
progress_bar.update(1)
|
| 175 |
+
|
| 176 |
+
return {
|
| 177 |
+
'image_name': image_name,
|
| 178 |
+
'min_size': min_size,
|
| 179 |
+
'start_size': start_size,
|
| 180 |
+
'threshold': threshold,
|
| 181 |
+
'color_quantization': color_quantization,
|
| 182 |
+
'tile_library': tile_library,
|
| 183 |
+
'success': False,
|
| 184 |
+
'error': str(e),
|
| 185 |
+
'MSE': float('nan'),
|
| 186 |
+
'SSIM': float('nan'),
|
| 187 |
+
'Histogram_Correlation': float('nan'),
|
| 188 |
+
'Edge_Similarity': float('nan'),
|
| 189 |
+
'Overall_Quality': float('nan')
|
| 190 |
+
}
|
| 191 |
+
|
| 192 |
+
def run_comprehensive_test():
|
| 193 |
+
"""Run comprehensive test across all parameter combinations"""
|
| 194 |
+
setup_directories()
|
| 195 |
+
|
| 196 |
+
# Find all image files in samples directory
|
| 197 |
+
image_files = []
|
| 198 |
+
for ext in ['*.jpg', '*.jpeg', '*.JPG', '*.JPEG', '*.png', '*.PNG']:
|
| 199 |
+
image_files.extend(list(SAMPLES_DIR.glob(ext)))
|
| 200 |
+
|
| 201 |
+
if not image_files:
|
| 202 |
+
print(f"[ERROR] No image files found in {SAMPLES_DIR}")
|
| 203 |
+
return
|
| 204 |
+
|
| 205 |
+
print(f"[INFO] Found {len(image_files)} images to process")
|
| 206 |
+
print(f"[INFO] Images: {[f.name for f in image_files]}")
|
| 207 |
+
|
| 208 |
+
# Generate all parameter combinations
|
| 209 |
+
param_combinations = list(product(
|
| 210 |
+
TEST_PARAMS['min_size'],
|
| 211 |
+
TEST_PARAMS['start_size'],
|
| 212 |
+
TEST_PARAMS['threshold'],
|
| 213 |
+
TEST_PARAMS['color_quantization'],
|
| 214 |
+
TEST_PARAMS['tile_library']
|
| 215 |
+
))
|
| 216 |
+
|
| 217 |
+
# Filter out invalid combinations (min_size >= start_size)
|
| 218 |
+
valid_combinations = [
|
| 219 |
+
combo for combo in param_combinations
|
| 220 |
+
if combo[0] < combo[1] # min_size < start_size
|
| 221 |
+
]
|
| 222 |
+
|
| 223 |
+
total_tests = len(image_files) * len(valid_combinations)
|
| 224 |
+
print(f"[INFO] Total test combinations: {total_tests}")
|
| 225 |
+
print(f"[INFO] Parameter combinations per image: {len(valid_combinations)}")
|
| 226 |
+
|
| 227 |
+
# Results storage
|
| 228 |
+
all_results = []
|
| 229 |
+
|
| 230 |
+
# Create progress bar
|
| 231 |
+
with tqdm(total=total_tests, desc="Processing mosaics", unit="test") as pbar:
|
| 232 |
+
for image_path in image_files:
|
| 233 |
+
print(f"\n[INFO] Processing image: {image_path.name}")
|
| 234 |
+
|
| 235 |
+
for params in valid_combinations:
|
| 236 |
+
result = process_single_combination(image_path, params, pbar)
|
| 237 |
+
all_results.append(result)
|
| 238 |
+
|
| 239 |
+
# Save comprehensive results to CSV
|
| 240 |
+
summary_path = OUTPUT_DIR / 'summary.csv'
|
| 241 |
+
df = pd.DataFrame(all_results)
|
| 242 |
+
df.to_csv(summary_path, index=False)
|
| 243 |
+
|
| 244 |
+
# Print summary statistics
|
| 245 |
+
successful_tests = df[df['success'] == True]
|
| 246 |
+
failed_tests = df[df['success'] == False]
|
| 247 |
+
|
| 248 |
+
print(f"\n[SUMMARY]")
|
| 249 |
+
print(f"Total tests run: {len(all_results)}")
|
| 250 |
+
print(f"Successful: {len(successful_tests)}")
|
| 251 |
+
print(f"Failed: {len(failed_tests)}")
|
| 252 |
+
|
| 253 |
+
if len(successful_tests) > 0:
|
| 254 |
+
print(f"\nPerformance Statistics (successful tests):")
|
| 255 |
+
print(f"Average MSE: {successful_tests['MSE'].mean():.2f}")
|
| 256 |
+
print(f"Average SSIM: {successful_tests['SSIM'].mean():.4f}")
|
| 257 |
+
print(f"Average Histogram Correlation: {successful_tests['Histogram_Correlation'].mean():.4f}")
|
| 258 |
+
print(f"Average Edge Similarity: {successful_tests['Edge_Similarity'].mean():.4f}")
|
| 259 |
+
print(f"Average Overall Quality: {successful_tests['Overall_Quality'].mean():.4f}")
|
| 260 |
+
|
| 261 |
+
print(f"\nResults saved to:")
|
| 262 |
+
print(f"- Summary CSV: {summary_path}")
|
| 263 |
+
print(f"- Mosaic images: {MOSAIC_DIR}")
|
| 264 |
+
print(f"- Individual metrics: {METRICS_DIR}")
|
| 265 |
+
|
| 266 |
+
return all_results
|
| 267 |
+
|
| 268 |
+
if __name__ == "__main__":
|
| 269 |
+
print("=" * 60)
|
| 270 |
+
print("Interactive Image Mosaic Generator - Comprehensive Test")
|
| 271 |
+
print("=" * 60)
|
| 272 |
+
|
| 273 |
+
results = run_comprehensive_test()
|
| 274 |
+
|
| 275 |
+
print("\n" + "=" * 60)
|
| 276 |
+
print("Test completed successfully!")
|
| 277 |
+
print("=" * 60)
|