| |
| """ |
| 生成按退化类型分类的详细表格 |
| |
| 输出格式: |
| Corruption Category novel_ap50_PC_c novel_ap50_rPC(%) base_ap50_PC_c base_ap50_rPC(%) all_ap50_PC_c all_ap50_rPC(%) |
| gaussian_noise noise 27.32 72.83 38.18 69.50 35.34 70.15 |
| shot_noise noise 27.17 72.43 37.67 68.57 34.92 69.32 |
| ... |
| """ |
|
|
| import os |
| import json |
| import argparse |
| import pickle |
|
|
| try: |
| import pandas as pd |
| HAS_PANDAS = True |
| except ImportError: |
| HAS_PANDAS = False |
| print("Warning: pandas not installed, Excel output disabled") |
|
|
| |
| BENCHMARK_CORRUPTIONS = [ |
| 'gaussian_noise', 'shot_noise', 'impulse_noise', |
| 'defocus_blur', 'glass_blur', 'motion_blur', 'zoom_blur', |
| 'snow', 'frost', 'fog', 'brightness', |
| 'contrast', 'elastic_transform', 'pixelate', 'jpeg_compression' |
| ] |
|
|
| |
| CORRUPTION_CATEGORIES = { |
| 'gaussian_noise': 'noise', |
| 'shot_noise': 'noise', |
| 'impulse_noise': 'noise', |
| 'defocus_blur': 'blur', |
| 'glass_blur': 'blur', |
| 'motion_blur': 'blur', |
| 'zoom_blur': 'blur', |
| 'snow': 'weather', |
| 'frost': 'weather', |
| 'fog': 'weather', |
| 'brightness': 'weather', |
| 'contrast': 'digital', |
| 'elastic_transform': 'digital', |
| 'pixelate': 'digital', |
| 'jpeg_compression': 'digital' |
| } |
|
|
| |
| PREDEFINED_CLEAN_METRICS = { |
| 'clearclip': { |
| 'base_ap50': 44.00, |
| 'novel_ap50': 26.74, |
| 'all_ap50': 39.49, |
| }, |
| 'clipself': { |
| 'base_ap50': 54.94, |
| 'novel_ap50': 37.51, |
| 'all_ap50': 50.38, |
| } |
| } |
|
|
|
|
| def load_model_results(results_dir, model_name): |
| """加载单个模型的结果""" |
| |
| pkl_path = os.path.join(results_dir, 'merged_results.pkl') |
| if os.path.exists(pkl_path): |
| with open(pkl_path, 'rb') as f: |
| data = pickle.load(f) |
| return data |
| |
| |
| json_path = os.path.join(results_dir, 'robustness_summary.json') |
| if os.path.exists(json_path): |
| with open(json_path, 'r') as f: |
| return {'robustness_results': json.load(f)} |
| |
| return None |
|
|
|
|
| def get_clean_metrics(model_name): |
| """获取模型的 clean metrics""" |
| model_key = model_name.lower().replace('-', '').replace('_', '') |
| for key, metrics in PREDEFINED_CLEAN_METRICS.items(): |
| if key in model_key or model_key in key: |
| return metrics.copy() |
| return {} |
|
|
|
|
| def generate_corruption_table(results_dir, model_name): |
| """生成按退化类型的详细表格""" |
| data = load_model_results(results_dir, model_name) |
| if data is None: |
| print(f"ERROR: Could not load results from {results_dir}") |
| return None |
| |
| robustness = data.get('robustness_results', data) |
| corruption_avg = robustness.get('corruption_avg', {}) |
| |
| |
| p_clean = robustness.get('P', robustness.get('P_clean', {})) |
| if not p_clean: |
| p_clean = get_clean_metrics(model_name) |
| |
| rows = [] |
| for corr in BENCHMARK_CORRUPTIONS: |
| category = CORRUPTION_CATEGORIES.get(corr, 'unknown') |
| corr_data = corruption_avg.get(corr, {}) |
| |
| row = { |
| 'Corruption': corr, |
| 'Category': category, |
| } |
| |
| for metric in ['novel_ap50', 'base_ap50', 'all_ap50']: |
| pc_c = corr_data.get(metric) |
| p_clean_val = p_clean.get(metric) |
| |
| |
| row[f'{metric}_PC_c'] = round(pc_c, 2) if pc_c is not None else None |
| |
| |
| if pc_c is not None and p_clean_val is not None and p_clean_val > 0: |
| rpc = (pc_c / p_clean_val) * 100 |
| row[f'{metric}_rPC(%)'] = round(rpc, 2) |
| else: |
| row[f'{metric}_rPC(%)'] = None |
| |
| rows.append(row) |
| |
| return rows, p_clean |
|
|
|
|
| def print_corruption_table(rows, model_name, p_clean): |
| """打印退化类型表格""" |
| print(f"\n{'='*120}") |
| print(f"Corruption-level Performance: {model_name}") |
| print(f"P_clean: novel_ap50={p_clean.get('novel_ap50')}, base_ap50={p_clean.get('base_ap50')}, all_ap50={p_clean.get('all_ap50')}") |
| print(f"{'='*120}") |
| |
| |
| header = f"{'Corruption':<20} {'Category':<10}" |
| for metric in ['novel_ap50', 'base_ap50', 'all_ap50']: |
| header += f" {metric+'_PC_c':>14} {metric+'_rPC(%)':>14}" |
| print(header) |
| print("-" * 120) |
| |
| |
| for row in rows: |
| line = f"{row['Corruption']:<20} {row['Category']:<10}" |
| for metric in ['novel_ap50', 'base_ap50', 'all_ap50']: |
| pc_c = row.get(f'{metric}_PC_c') |
| rpc = row.get(f'{metric}_rPC(%)') |
| pc_c_str = f"{pc_c:.2f}" if pc_c is not None else "N/A" |
| rpc_str = f"{rpc:.2f}" if rpc is not None else "N/A" |
| line += f" {pc_c_str:>14} {rpc_str:>14}" |
| print(line) |
| |
| print("=" * 120) |
|
|
|
|
| def save_corruption_table_excel(all_tables, output_path): |
| """保存所有模型的退化类型表格到 Excel""" |
| if not HAS_PANDAS: |
| print("ERROR: pandas not installed, cannot save Excel") |
| return |
| |
| columns = ['Corruption', 'Category', |
| 'novel_ap50_PC_c', 'novel_ap50_rPC(%)', |
| 'base_ap50_PC_c', 'base_ap50_rPC(%)', |
| 'all_ap50_PC_c', 'all_ap50_rPC(%)'] |
| |
| with pd.ExcelWriter(output_path, engine='openpyxl') as writer: |
| for model_name, (rows, p_clean) in all_tables.items(): |
| |
| df = pd.DataFrame(rows) |
| df = df[columns] |
| |
| |
| mpc = {} |
| for metric in ['novel_ap50', 'base_ap50', 'all_ap50']: |
| values = [row.get(f'{metric}_PC_c') for row in rows if row.get(f'{metric}_PC_c') is not None] |
| if values: |
| mpc[metric] = sum(values) / len(values) |
| |
| |
| rpc = {} |
| for metric in ['novel_ap50', 'base_ap50', 'all_ap50']: |
| if mpc.get(metric) and p_clean.get(metric): |
| rpc[metric] = (mpc[metric] / p_clean[metric]) * 100 |
| |
| |
| summary_rows = [ |
| |
| {col: None for col in columns}, |
| |
| { |
| 'Corruption': 'P_clean', |
| 'Category': None, |
| 'novel_ap50_PC_c': p_clean.get('novel_ap50'), |
| 'novel_ap50_rPC(%)': None, |
| 'base_ap50_PC_c': p_clean.get('base_ap50'), |
| 'base_ap50_rPC(%)': None, |
| 'all_ap50_PC_c': p_clean.get('all_ap50'), |
| 'all_ap50_rPC(%)': None, |
| }, |
| |
| { |
| 'Corruption': 'mPC', |
| 'Category': None, |
| 'novel_ap50_PC_c': round(mpc.get('novel_ap50', 0), 2), |
| 'novel_ap50_rPC(%)': round(rpc.get('novel_ap50', 0), 2), |
| 'base_ap50_PC_c': round(mpc.get('base_ap50', 0), 2), |
| 'base_ap50_rPC(%)': round(rpc.get('base_ap50', 0), 2), |
| 'all_ap50_PC_c': round(mpc.get('all_ap50', 0), 2), |
| 'all_ap50_rPC(%)': round(rpc.get('all_ap50', 0), 2), |
| }, |
| ] |
| |
| df_summary = pd.DataFrame(summary_rows, columns=columns) |
| |
| |
| df_full = pd.concat([df, df_summary], ignore_index=True) |
| df_full.to_excel(writer, sheet_name=model_name, index=False) |
| |
| print(f"Corruption table Excel saved to: {output_path}") |
|
|
|
|
| def save_corruption_table_json(all_tables, output_path): |
| """保存所有模型的退化类型表格到 JSON""" |
| result = {} |
| for model_name, (rows, p_clean) in all_tables.items(): |
| result[model_name] = { |
| 'P_clean': p_clean, |
| 'corruption_details': rows |
| } |
| |
| with open(output_path, 'w') as f: |
| json.dump(result, f, indent=2) |
| print(f"Corruption table JSON saved to: {output_path}") |
|
|
|
|
| def main(): |
| parser = argparse.ArgumentParser(description='Generate corruption-level performance table') |
| parser.add_argument('--results-dirs', type=str, nargs='+', required=True, |
| help='Directories containing model results') |
| parser.add_argument('--model-names', type=str, nargs='+', default=None, |
| help='Model names (default: infer from directory names)') |
| parser.add_argument('--output-dir', type=str, default='.', |
| help='Output directory') |
| parser.add_argument('--output-prefix', type=str, default='corruption_table', |
| help='Output file prefix') |
| args = parser.parse_args() |
| |
| |
| if args.model_names is None: |
| args.model_names = [os.path.basename(d.rstrip('/')) for d in args.results_dirs] |
| |
| if len(args.model_names) != len(args.results_dirs): |
| print("ERROR: Number of model names must match number of results directories") |
| return |
| |
| |
| all_tables = {} |
| for results_dir, model_name in zip(args.results_dirs, args.model_names): |
| print(f"Generating table for {model_name} from {results_dir}...") |
| result = generate_corruption_table(results_dir, model_name) |
| if result: |
| rows, p_clean = result |
| all_tables[model_name] = (rows, p_clean) |
| print_corruption_table(rows, model_name, p_clean) |
| |
| if not all_tables: |
| print("ERROR: No valid results found!") |
| return |
| |
| |
| os.makedirs(args.output_dir, exist_ok=True) |
| |
| excel_path = os.path.join(args.output_dir, f'{args.output_prefix}.xlsx') |
| save_corruption_table_excel(all_tables, excel_path) |
| |
| json_path = os.path.join(args.output_dir, f'{args.output_prefix}.json') |
| save_corruption_table_json(all_tables, json_path) |
|
|
|
|
| if __name__ == '__main__': |
| main() |
|
|