xiaomoguhzz's picture
Add files using upload-large-folder tool
eba0a14 verified
#!/usr/bin/env python
"""
批量运行鲁棒性评估脚本
该脚本会遍历所有常见的图像退化类型和严重程度,在Cityscapes数据集上评估模型性能。
使用方法:
python robustness_eval/run_robustness_eval.py \
--config configs/eva_declip/cfg_city_scapes_robust.py \
--work-dir work_logs/robustness_eval \
--corruptions common \
--severities 1 2 3 4 5
"""
import os
import sys
import argparse
import subprocess
import json
from pathlib import Path
from imagecorruptions import get_corruption_names
# 添加项目根目录到路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
from robustness_eval.prepare_corrupted_images import (
corrupt_and_save_images,
cleanup_tmp_directory
)
def parse_args():
parser = argparse.ArgumentParser(
description='批量运行鲁棒性评估')
parser.add_argument(
'--config',
type=str,
default='configs/eva_declip/cfg_city_scapes_robust.py',
help='配置文件路径')
parser.add_argument(
'--work-dir',
type=str,
default='robustness_eval/results',
help='工作目录,用于保存结果(默认: robustness_eval/results)')
parser.add_argument(
'--corruptions',
type=str,
choices=['common', 'validation', 'all', 'noise', 'blur', 'weather', 'digital'],
default='common',
help='退化类型子集')
parser.add_argument(
'--severities',
type=int,
nargs='+',
default=[1, 2, 3, 4, 5],
help='严重程度级别列表')
parser.add_argument(
'--clean-only',
action='store_true',
help='只运行干净图像的评估(baseline)')
parser.add_argument(
'--skip-clean',
action='store_true',
help='跳过干净图像的评估')
parser.add_argument(
'--parallel',
type=int,
default=1,
help='并行运行的进程数(1表示串行)')
parser.add_argument(
'--resume',
action='store_true',
help='从上次中断的地方继续(跳过已完成的评估)')
return parser.parse_args()
def get_eval_script_path():
"""获取eval.py脚本的路径"""
return project_root / 'eval.py'
def get_dataset_info_from_config(config_path):
"""从配置文件中读取数据集信息
读取原始数据集的data_root和img_path_prefix,用于图片预处理
"""
from mmengine.config import Config
# 临时保存并清除CORRUPTED_DATA_ROOT,以获取原始配置
original_corrupted_root = os.environ.pop('CORRUPTED_DATA_ROOT', None)
try:
cfg = Config.fromfile(str(config_path))
# 读取data_root(允许为空,保持原配置含义)
data_root = cfg.get('data_root', '')
# 获取img_path_prefix;若为绝对路径则直接使用
data_prefix = cfg.test_dataloader.dataset.get('data_prefix', {})
img_path_prefix = data_prefix.get('img_path', 'leftImg8bit/val')
return data_root, img_path_prefix
finally:
# 恢复环境变量
if original_corrupted_root is not None:
os.environ['CORRUPTED_DATA_ROOT'] = original_corrupted_root
def run_single_eval(config_path, corruption_name, severity, work_dir_base,
source_data_root=None, source_img_prefix=None):
"""运行单次评估
Args:
config_path: 配置文件路径
corruption_name: corruption类型名称
severity: 严重程度
work_dir_base: 工作目录基础路径
source_data_root: 源数据集根目录(如果为None,则从配置文件读取)
source_img_prefix: 源图片相对路径前缀(如果为None,则从配置文件读取)
"""
# 确保工作目录是绝对路径
work_dir_base = Path(work_dir_base)
if not work_dir_base.is_absolute():
work_dir_base = project_root / work_dir_base
# 创建工作目录
if corruption_name == 'clean':
work_dir = work_dir_base / corruption_name
else:
work_dir = work_dir_base / corruption_name / f'severity_{severity}'
work_dir.mkdir(parents=True, exist_ok=True)
# 从配置文件读取数据集信息(如果未提供)
if source_data_root is None or source_img_prefix is None:
cfg_data_root, cfg_img_prefix = get_dataset_info_from_config(config_path)
if source_data_root is None:
source_data_root = cfg_data_root
if source_img_prefix is None:
source_img_prefix = cfg_img_prefix
# 准备corrupt图片到临时目录
tmp_dir = None
try:
# 创建临时目录
tmp_base = work_dir_base / 'tmp_corrupted_images'
if corruption_name == 'clean':
tmp_dir = tmp_base / 'clean'
else:
tmp_dir = tmp_base / corruption_name / f'severity_{severity}'
print(f"\n{'='*80}")
print(f"准备图片: {corruption_name}, severity={severity}")
print(f"源目录: {source_data_root}")
print(f"临时目录: {tmp_dir}")
print(f"{'='*80}\n")
# 预处理图片(应用corruption并保存到tmp目录)
target_data_root = corrupt_and_save_images(
source_data_root=source_data_root,
source_img_prefix=source_img_prefix,
target_tmp_root=str(tmp_dir),
corruption_name=corruption_name,
severity=severity
)
# 设置环境变量,告诉配置文件使用临时目录
env = os.environ.copy()
env['CORRUPTED_DATA_ROOT'] = target_data_root
env['CORRUPTION_NAME'] = corruption_name
if corruption_name != 'clean':
env['SEVERITY'] = str(severity)
else:
env['SEVERITY'] = '1' # clean时severity不重要,但需要设置
# 构建命令
eval_script = get_eval_script_path()
cmd = [
sys.executable,
str(eval_script),
'--config', str(config_path),
'--work-dir', str(work_dir)
]
# 运行评估
print(f"\n{'='*80}")
print(f"运行评估: {corruption_name}, severity={severity}")
print(f"工作目录: {work_dir}")
print(f"使用数据目录: {target_data_root}")
print(f"{'='*80}\n")
result = subprocess.run(cmd, env=env, cwd=project_root)
if result.returncode == 0:
print(f"✓ 完成: {corruption_name}, severity={severity}")
success = True
else:
print(f"✗ 失败: {corruption_name}, severity={severity}")
success = False
return success, work_dir
finally:
# 清理临时目录
if tmp_dir and tmp_dir.exists():
print(f"\n清理临时目录: {tmp_dir}")
cleanup_tmp_directory(str(tmp_dir))
def load_results(work_dir):
"""从工作目录加载评估结果"""
results_file = Path(work_dir) / 'results.txt'
if not results_file.exists():
return None
results = {}
with open(results_file, 'r') as f:
lines = f.readlines()
for line in lines:
if ':' in line:
key, value = line.strip().split(':', 1)
key = key.strip()
value = value.strip()
# 尝试转换为数字
try:
if '.' in value:
value = float(value)
else:
value = int(value)
except ValueError:
pass
results[key] = value
return results
def check_if_done(work_dir):
"""检查评估是否已完成"""
results_file = Path(work_dir) / 'results.txt'
if results_file.exists():
# 检查是否包含mIoU结果
with open(results_file, 'r') as f:
content = f.read()
if 'mIoU' in content or 'aAcc' in content:
return True
return False
def main():
args = parse_args()
# 获取配置文件路径
config_path = Path(args.config)
if not config_path.is_absolute():
config_path = project_root / config_path
if not config_path.exists():
print(f"错误: 配置文件不存在: {config_path}")
return
# 获取退化类型列表
if args.clean_only:
corruption_list = ['clean']
else:
corruption_list = get_corruption_names(args.corruptions)
if not args.skip_clean:
corruption_list = ['clean'] + corruption_list
# 准备所有评估任务
tasks = []
for corruption in corruption_list:
if corruption == 'clean':
# 干净图像只需要评估一次
tasks.append(('clean', 1)) # severity设为1,但实际不会被使用
else:
for severity in args.severities:
tasks.append((corruption, severity))
print(f"\n{'='*80}")
print(f"鲁棒性评估计划")
print(f"{'='*80}")
print(f"配置文件: {config_path}")
print(f"工作目录: {args.work_dir}")
print(f"退化类型: {args.corruptions} ({len(corruption_list)} 种)")
print(f"严重程度: {args.severities}")
print(f"总任务数: {len(tasks)}")
print(f"{'='*80}\n")
# 确保工作目录是绝对路径
work_dir_base = Path(args.work_dir)
if not work_dir_base.is_absolute():
work_dir_base = project_root / work_dir_base
# 先加载已有的结果(如果存在),以便合并
summary_file = work_dir_base / 'results_summary.json'
results_summary = {}
if summary_file.exists():
try:
with open(summary_file, 'r') as f:
results_summary = json.load(f)
except:
pass
# 运行评估
completed = 0
failed = 0
skipped = 0
for corruption, severity in tasks:
if corruption == 'clean':
corruption_name = 'clean'
severity_display = 'N/A'
severity_for_result = 0 # 用于结果存储
else:
corruption_name = corruption
severity_display = severity
severity_for_result = severity
# 确保工作目录是绝对路径
work_dir_base = Path(args.work_dir)
if not work_dir_base.is_absolute():
work_dir_base = project_root / work_dir_base
work_dir = work_dir_base / corruption_name
if corruption != 'clean':
work_dir = work_dir / f'severity_{severity}'
# 检查是否需要跳过
if args.resume and check_if_done(work_dir):
print(f"⊘ 跳过已完成: {corruption_name}, severity={severity_display}")
skipped += 1
# 加载已有结果
result = load_results(work_dir)
if result:
if corruption_name not in results_summary:
results_summary[corruption_name] = {}
results_summary[corruption_name][severity_for_result] = result
continue
# 运行评估
success, work_dir_actual = run_single_eval(
config_path, corruption_name, severity, args.work_dir,
source_data_root=None, source_img_prefix=None)
if success:
completed += 1
# 加载结果
result = load_results(work_dir_actual)
if result:
if corruption_name not in results_summary:
results_summary[corruption_name] = {}
results_summary[corruption_name][severity_for_result] = result
else:
failed += 1
# 保存汇总结果
summary_file = work_dir_base / 'results_summary.json'
summary_file.parent.mkdir(parents=True, exist_ok=True)
with open(summary_file, 'w') as f:
json.dump(results_summary, f, indent=2)
# 打印汇总
print(f"\n{'='*80}")
print(f"评估完成汇总")
print(f"{'='*80}")
print(f"总任务数: {len(tasks)}")
print(f"已完成: {completed}")
print(f"已跳过: {skipped}")
print(f"失败: {failed}")
print(f"结果汇总已保存到: {summary_file}")
print(f"{'='*80}\n")
# 生成Excel文件(解耦:不在这里生成,由用户单独调用)
# Excel生成已解耦,用户可以在所有任务完成后单独调用save_results_to_excel.py
if __name__ == '__main__':
main()