diff --git a/src/enhance_pedestrian_safety/data_analyzer.py b/src/enhance_pedestrian_safety/data_analyzer.py new file mode 100644 index 0000000000..a5802c2dc4 --- /dev/null +++ b/src/enhance_pedestrian_safety/data_analyzer.py @@ -0,0 +1,337 @@ +import os +import json +import numpy as np +from collections import defaultdict + + +class DataAnalyzer: + """数据分析器 - 生成数据集统计信息""" + + @staticmethod + def analyze_dataset(data_dir): + """分析数据集并生成详细报告""" + print(f"分析数据集: {data_dir}") + + analysis = { + 'basic_stats': DataAnalyzer._get_basic_stats(data_dir), + 'file_distribution': DataAnalyzer._analyze_file_distribution(data_dir), + 'object_statistics': DataAnalyzer._analyze_objects(data_dir), + 'temporal_analysis': DataAnalyzer._analyze_temporal(data_dir), + 'quality_metrics': DataAnalyzer._calculate_quality_metrics(data_dir) + } + + # 生成评分 + analysis['overall_score'] = DataAnalyzer._calculate_overall_score(analysis) + + # 保存分析结果 + DataAnalyzer._save_analysis_report(data_dir, analysis) + + # 打印摘要 + DataAnalyzer._print_analysis_summary(analysis) + + return analysis + + @staticmethod + def _get_basic_stats(data_dir): + """获取基本统计信息""" + stats = { + 'total_size_mb': DataAnalyzer._get_directory_size(data_dir), + 'file_count': 0, + 'directory_count': 0, + 'data_types': defaultdict(int) + } + + for root, dirs, files in os.walk(data_dir): + stats['directory_count'] += len(dirs) + stats['file_count'] += len(files) + + for file in files: + ext = os.path.splitext(file)[1].lower() + if ext in ['.png', '.jpg', '.jpeg']: + stats['data_types']['images'] += 1 + elif ext == '.json': + stats['data_types']['json'] += 1 + elif ext == '.txt': + stats['data_types']['text'] += 1 + elif ext == '.bin': + stats['data_types']['binary'] += 1 + else: + stats['data_types']['other'] += 1 + + return stats + + @staticmethod + def _get_directory_size(path): + """计算目录大小""" + total = 0 + for dirpath, dirnames, filenames in os.walk(path): + for f in filenames: + fp = os.path.join(dirpath, f) + if os.path.exists(fp): + total += os.path.getsize(fp) + return round(total / (1024 * 1024), 2) + + @staticmethod + def _analyze_file_distribution(data_dir): + """分析文件分布""" + distribution = {} + + # 分析原始图像 + raw_dirs = ['vehicle', 'infrastructure'] + for raw_dir in raw_dirs: + path = os.path.join(data_dir, "raw", raw_dir) + if os.path.exists(path): + camera_stats = {} + for camera_dir in os.listdir(path): + camera_path = os.path.join(path, camera_dir) + if os.path.isdir(camera_path): + images = [f for f in os.listdir(camera_path) + if f.endswith(('.png', '.jpg', '.jpeg'))] + camera_stats[camera_dir] = len(images) + distribution[f'raw_{raw_dir}'] = camera_stats + + # 分析拼接图像 + stitched_dir = os.path.join(data_dir, "stitched") + if os.path.exists(stitched_dir): + stitched_images = [f for f in os.listdir(stitched_dir) + if f.endswith(('.jpg', '.jpeg', '.png'))] + distribution['stitched'] = len(stitched_images) + + # 分析标注文件 + annotations_dir = os.path.join(data_dir, "annotations") + if os.path.exists(annotations_dir): + json_files = [f for f in os.listdir(annotations_dir) if f.endswith('.json')] + distribution['annotations'] = len(json_files) + + return distribution + + @staticmethod + def _analyze_objects(data_dir): + """分析物体统计""" + annotations_dir = os.path.join(data_dir, "annotations") + + if not os.path.exists(annotations_dir): + return {'total_objects': 0, 'by_class': {}, 'by_frame': {}} + + object_stats = { + 'total_objects': 0, + 'by_class': defaultdict(int), + 'by_frame': defaultdict(int), + 'class_distribution': {} + } + + json_files = [f for f in os.listdir(annotations_dir) + if f.endswith('.json') and f.startswith('frame_')] + + for json_file in json_files: + try: + with open(os.path.join(annotations_dir, json_file), 'r') as f: + data = json.load(f) + + frame_id = data.get('frame_id', 0) + objects = data.get('objects', []) + + object_stats['by_frame'][frame_id] = len(objects) + object_stats['total_objects'] += len(objects) + + for obj in objects: + obj_class = obj.get('class', 'unknown') + object_stats['by_class'][obj_class] += 1 + + except Exception as e: + print(f"分析标注文件 {json_file} 失败: {e}") + + # 计算类分布百分比 + if object_stats['total_objects'] > 0: + for obj_class, count in object_stats['by_class'].items(): + object_stats['class_distribution'][obj_class] = round( + count / object_stats['total_objects'] * 100, 2) + + return object_stats + + @staticmethod + def _analyze_temporal(data_dir): + """分析时间分布""" + temporal_stats = { + 'frame_intervals': [], + 'total_duration': 0, + 'frame_rate': 0 + } + + metadata_file = os.path.join(data_dir, "metadata", "collection_info.json") + if os.path.exists(metadata_file): + try: + with open(metadata_file, 'r') as f: + metadata = json.load(f) + + collection_stats = metadata.get('collection_stats', {}) + temporal_stats['total_duration'] = collection_stats.get('duration_seconds', 0) + temporal_stats['frame_rate'] = collection_stats.get('average_fps', 0) + + except Exception as e: + print(f"分析元数据失败: {e}") + + return temporal_stats + + @staticmethod + def _calculate_quality_metrics(data_dir): + """计算质量指标""" + quality_metrics = { + 'completeness_score': 0, + 'consistency_score': 0, + 'diversity_score': 0, + 'issues_found': [] + } + + # 检查完整性 + required_dirs = ["raw/vehicle", "raw/infrastructure", "stitched", "metadata"] + missing_dirs = [] + + for dir_path in required_dirs: + if not os.path.exists(os.path.join(data_dir, dir_path)): + missing_dirs.append(dir_path) + + if missing_dirs: + quality_metrics['issues_found'].append(f"缺失目录: {missing_dirs}") + quality_metrics['completeness_score'] = 50 + else: + quality_metrics['completeness_score'] = 100 + + # 检查一致性(图像数量) + raw_vehicle = os.path.join(data_dir, "raw", "vehicle") + if os.path.exists(raw_vehicle): + camera_counts = [] + for camera_dir in os.listdir(raw_vehicle): + camera_path = os.path.join(raw_vehicle, camera_dir) + if os.path.isdir(camera_path): + images = [f for f in os.listdir(camera_path) + if f.endswith('.png')] + camera_counts.append(len(images)) + + if camera_counts: + max_diff = max(camera_counts) - min(camera_counts) + if max_diff > 5: + quality_metrics['issues_found'].append(f"摄像头图像数量不一致: 差异{max_diff}") + quality_metrics['consistency_score'] = 70 + else: + quality_metrics['consistency_score'] = 95 + + # 多样性评分(基于物体类别) + object_stats = DataAnalyzer._analyze_objects(data_dir) + num_classes = len(object_stats.get('by_class', {})) + + if num_classes >= 5: + quality_metrics['diversity_score'] = 90 + elif num_classes >= 3: + quality_metrics['diversity_score'] = 70 + else: + quality_metrics['diversity_score'] = 50 + quality_metrics['issues_found'].append(f"物体类别较少: {num_classes}类") + + return quality_metrics + + @staticmethod + def _calculate_overall_score(analysis): + """计算总体评分""" + weights = { + 'completeness': 0.3, + 'consistency': 0.25, + 'diversity': 0.25, + 'temporal': 0.2 + } + + quality = analysis['quality_metrics'] + + score = ( + quality['completeness_score'] * weights['completeness'] + + quality['consistency_score'] * weights['consistency'] + + quality['diversity_score'] * weights['diversity'] + ) + + # 时间因素 + temporal = analysis['temporal_analysis'] + if temporal['frame_rate'] >= 2.0: + score += 20 * weights['temporal'] + elif temporal['frame_rate'] >= 1.0: + score += 15 * weights['temporal'] + else: + score += 5 * weights['temporal'] + + return round(score, 1) + + @staticmethod + def _save_analysis_report(data_dir, analysis): + """保存分析报告""" + report_file = os.path.join(data_dir, "metadata", "dataset_analysis.json") + + with open(report_file, 'w', encoding='utf-8') as f: + json.dump(analysis, f, indent=2, ensure_ascii=False) + + print(f"数据集分析报告保存: {report_file}") + + @staticmethod + def _print_analysis_summary(analysis): + """打印分析摘要""" + print("\n" + "=" * 60) + print("数据集分析摘要") + print("=" * 60) + + basic = analysis['basic_stats'] + print(f"\n基本统计:") + print(f" 总大小: {basic['total_size_mb']} MB") + print(f" 文件数: {basic['file_count']}") + print(f" 目录数: {basic['directory_count']}") + + print(f" 数据类型:") + for data_type, count in basic['data_types'].items(): + print(f" {data_type}: {count}") + + distribution = analysis['file_distribution'] + print(f"\n文件分布:") + for key, value in distribution.items(): + if isinstance(value, dict): + print(f" {key}:") + for subkey, subvalue in value.items(): + print(f" {subkey}: {subvalue}") + else: + print(f" {key}: {value}") + + objects = analysis['object_statistics'] + print(f"\n物体统计:") + print(f" 总物体数: {objects['total_objects']}") + if objects['by_class']: + print(f" 类别分布:") + for obj_class, count in objects['by_class'].items(): + percentage = objects['class_distribution'].get(obj_class, 0) + print(f" {obj_class}: {count} ({percentage}%)") + + temporal = analysis['temporal_analysis'] + print(f"\n时间分析:") + print(f" 总时长: {temporal['total_duration']:.1f}秒") + print(f" 平均帧率: {temporal['frame_rate']:.2f} FPS") + + quality = analysis['quality_metrics'] + print(f"\n质量指标:") + print(f" 完整性: {quality['completeness_score']}/100") + print(f" 一致性: {quality['consistency_score']}/100") + print(f" 多样性: {quality['diversity_score']}/100") + + if quality['issues_found']: + print(f" 发现的问题 ({len(quality['issues_found'])}):") + for issue in quality['issues_found'][:3]: + print(f" - {issue}") + if len(quality['issues_found']) > 3: + print(f" ... 还有 {len(quality['issues_found']) - 3} 个问题") + + print(f"\n总体评分: {analysis['overall_score']}/100") + + if analysis['overall_score'] >= 90: + print("✓ 数据集质量优秀") + elif analysis['overall_score'] >= 75: + print("✓ 数据集质量良好") + elif analysis['overall_score'] >= 60: + print("⚠ 数据集质量一般") + else: + print("✗ 数据集质量需要改进") + + print("=" * 60) \ No newline at end of file diff --git a/src/enhance_pedestrian_safety/main.py b/src/enhance_pedestrian_safety/main.py index 75a9e71d6f..2413be884f 100644 --- a/src/enhance_pedestrian_safety/main.py +++ b/src/enhance_pedestrian_safety/main.py @@ -8,18 +8,22 @@ import threading import json from datetime import datetime -from collections import deque +from collections import defaultdict from carla_utils import setup_carla_path, import_carla_module from config_manager import ConfigManager from annotation_generator import AnnotationGenerator from data_validator import DataValidator +from scene_manager import SceneManager +from data_analyzer import DataAnalyzer carla_egg_path, remaining_argv = setup_carla_path() carla = import_carla_module() -class Logger: +class Log: + """简单日志类""" + @staticmethod def info(msg): print(f"[INFO] {msg}") @@ -37,140 +41,232 @@ def debug(msg): print(f"[DEBUG] {msg}") -class Config: - VEHICLE_TYPES = [ - 'vehicle.tesla.model3', - 'vehicle.audi.tt', - 'vehicle.mini.cooperst', - 'vehicle.nissan.micra' - ] +class WeatherSystem: + """天气管理系统""" + WEATHER_PRESETS = { + 'clear': {'cloudiness': 10, 'precipitation': 0, 'wind': 5}, + 'rainy': {'cloudiness': 90, 'precipitation': 80, 'wind': 15}, + 'cloudy': {'cloudiness': 70, 'precipitation': 10, 'wind': 10}, + 'foggy': {'cloudiness': 50, 'precipitation': 0, 'fog_density': 40}, + 'stormy': {'cloudiness': 95, 'precipitation': 90, 'wind': 25, 'fog_density': 20} + } -class WeatherManager: @staticmethod def create_weather(weather_type, time_of_day): weather = carla.WeatherParameters() - if weather_type == 'clear': - weather.cloudiness = 10.0 - elif weather_type == 'rainy': - weather.cloudiness = 90.0 - weather.precipitation = 80.0 - elif weather_type == 'cloudy': - weather.cloudiness = 70.0 + if weather_type in WeatherSystem.WEATHER_PRESETS: + preset = WeatherSystem.WEATHER_PRESETS[weather_type] + weather.cloudiness = preset.get('cloudiness', 30) + weather.precipitation = preset.get('precipitation', 0) + weather.wind_intensity = preset.get('wind', 5) + if 'fog_density' in preset: + weather.fog_density = preset['fog_density'] + # 时间设置 if time_of_day == 'noon': weather.sun_altitude_angle = 75 elif time_of_day == 'sunset': weather.sun_altitude_angle = 15 elif time_of_day == 'night': weather.sun_altitude_angle = -20 + elif time_of_day == 'morning': + weather.sun_altitude_angle = 30 + elif time_of_day == 'dawn': + weather.sun_altitude_angle = 5 return weather -class ImageStitcher: +class ImageProcessor: + """图像处理器 - 支持多种输出格式""" + def __init__(self, output_dir): self.output_dir = output_dir self.stitched_dir = os.path.join(output_dir, "stitched") os.makedirs(self.stitched_dir, exist_ok=True) - def stitch(self, image_paths, frame_num, view_type="vehicle"): + self.has_pil = self._check_pil() + + def _check_pil(self): try: - from PIL import Image, ImageDraw + from PIL import Image + return True except ImportError: - Logger.warning("PIL未安装,跳过图像拼接") + Log.warning("PIL未安装,图像处理功能受限") return False - positions = [(10, 10), (660, 10), (10, 390), (660, 390)] + def stitch_4_view(self, image_paths, frame_num, view_type="vehicle"): + """四视角拼接""" + if not self.has_pil: + return False + + try: + from PIL import Image, ImageDraw + + positions = [(10, 10), (660, 10), (10, 390), (660, 390)] + + canvas = Image.new('RGB', (640 * 2 + 20, 360 * 2 + 20), (40, 40, 40)) + draw = ImageDraw.Draw(canvas) + + for idx, (cam_name, img_path) in enumerate(list(image_paths.items())[:4]): + img = self._load_image(img_path) + canvas.paste(img, positions[idx]) + + label = cam_name.replace('_', ' ').title() + draw.text((positions[idx][0] + 5, positions[idx][1] + 5), + label, fill=(255, 255, 200)) + + # 添加帧信息和时间戳 + timestamp = datetime.now().strftime("%H:%M:%S") + draw.text((canvas.width // 2 - 100, 5), f"Frame {frame_num:06d}", + fill=(255, 255, 255)) + draw.text((canvas.width - 150, canvas.height - 25), timestamp, + fill=(200, 200, 200)) - canvas = Image.new('RGB', (640 * 2 + 20, 360 * 2 + 20), (40, 40, 40)) - draw = ImageDraw.Draw(canvas) + output_path = os.path.join(self.stitched_dir, f"{view_type}_{frame_num:06d}.jpg") + canvas.save(output_path, "JPEG", quality=95) + + return True + + except Exception as e: + Log.error(f"图像拼接失败: {e}") + return False + + def _load_image(self, img_path): + """加载图像,处理异常""" + if not self.has_pil: + return None + + try: + from PIL import Image - for idx, (cam_name, img_path) in enumerate(list(image_paths.items())[:4]): if img_path and os.path.exists(img_path): - try: - img = Image.open(img_path).resize((640, 360)) - except: - img = Image.new('RGB', (640, 360), (80, 80, 80)) - else: - img = Image.new('RGB', (640, 360), (80, 80, 80)) + img = Image.open(img_path) + return img.resize((640, 360)) - canvas.paste(img, positions[idx]) - draw.text((positions[idx][0] + 5, positions[idx][1] + 5), - cam_name, fill=(255, 255, 200)) + except Exception as e: + Log.debug(f"加载图像失败 {img_path}: {e}") + + # 返回灰色占位图像 + from PIL import Image + return Image.new('RGB', (640, 360), (80, 80, 80)) - output_path = os.path.join(self.stitched_dir, f"{view_type}_{frame_num:06d}.jpg") - canvas.save(output_path, "JPEG", quality=90) - return True +class TrafficManager: + """交通管理器 - 增强版""" -class TrafficSystem: def __init__(self, world, config): self.world = world self.config = config self.vehicles = [] self.pedestrians = [] + self.static_obstacles = [] - seed = config['scenario'].get('seed', 42) + # 设置随机种子 + seed = config['scenario'].get('seed', random.randint(1, 1000)) random.seed(seed) + Log.info(f"随机种子: {seed}") - def spawn_ego_vehicle(self): + def spawn_ego_vehicle(self, vehicle_type=None): + """生成主车""" blueprint_lib = self.world.get_blueprint_library() - for vtype in Config.VEHICLE_TYPES: - if blueprint_lib.filter(vtype): - vehicle_bp = random.choice(blueprint_lib.filter(vtype)) - break + if vehicle_type: + if blueprint_lib.filter(vehicle_type): + vehicle_bp = random.choice(blueprint_lib.filter(vehicle_type)) + else: + vehicle_bp = random.choice(blueprint_lib.filter('vehicle.*')) else: - vehicle_bp = random.choice(blueprint_lib.filter('vehicle.*')) + # 常用车辆类型 + common_vehicles = [ + 'vehicle.tesla.model3', + 'vehicle.audi.tt', + 'vehicle.mini.cooperst', + 'vehicle.nissan.micra', + 'vehicle.mercedes.coupe', + 'vehicle.bmw.grandtourer' + ] + + for vtype in common_vehicles: + if blueprint_lib.filter(vtype): + vehicle_bp = random.choice(blueprint_lib.filter(vtype)) + break + else: + vehicle_bp = random.choice(blueprint_lib.filter('vehicle.*')) spawn_points = self.world.get_map().get_spawn_points() if not spawn_points: + Log.error("没有可用的生成点") return None - spawn_point = random.choice(spawn_points) - try: - vehicle = self.world.spawn_actor(vehicle_bp, spawn_point) - vehicle.set_autopilot(True) - vehicle.apply_control(carla.VehicleControl(throttle=0.2)) - Logger.info(f"主车: {vehicle.type_id}") - return vehicle - except Exception as e: - Logger.warning(f"主车生成失败: {e}") - return None + # 尝试多个生成点 + for _ in range(3): + spawn_point = random.choice(spawn_points) + try: + vehicle = self.world.spawn_actor(vehicle_bp, spawn_point) + vehicle.set_autopilot(True) + + # 初始控制 + control = carla.VehicleControl() + control.throttle = 0.3 + control.steer = random.uniform(-0.1, 0.1) + vehicle.apply_control(control) - def spawn_background_vehicles(self): + Log.info(f"主车: {vehicle.type_id}") + return vehicle + + except Exception as e: + Log.debug(f"车辆生成失败: {e}") + + return None + + def spawn_traffic(self, center_location, num_vehicles=8, num_pedestrians=6): + """生成交通""" + vehicles_spawned = self._spawn_vehicles(center_location, num_vehicles) + pedestrians_spawned = self._spawn_pedestrians(center_location, num_pedestrians) + + Log.info(f"交通生成: {vehicles_spawned}辆车, {pedestrians_spawned}个行人") + return vehicles_spawned + pedestrians_spawned + + def _spawn_vehicles(self, center_location, count): + """生成车辆""" blueprint_lib = self.world.get_blueprint_library() spawn_points = self.world.get_map().get_spawn_points() if not spawn_points: return 0 - num_vehicles = min(self.config['traffic']['background_vehicles'], 10) spawned = 0 - - for _ in range(num_vehicles): + for i in range(min(count, 15)): try: vehicle_bp = random.choice(blueprint_lib.filter('vehicle.*')) spawn_point = random.choice(spawn_points) + vehicle = self.world.spawn_actor(vehicle_bp, spawn_point) vehicle.set_autopilot(True) + + # 设置不同速度 + speed_factor = random.uniform(0.6, 1.2) + control = carla.VehicleControl() + control.throttle = 0.25 * speed_factor + vehicle.apply_control(control) + self.vehicles.append(vehicle) spawned += 1 - except: - pass - Logger.info(f"背景车辆: {spawned} 辆") + except Exception as e: + Log.debug(f"背景车辆生成失败: {e}") + return spawned - def spawn_pedestrians(self, center_location): + def _spawn_pedestrians(self, center_location, count): + """生成行人""" blueprint_lib = self.world.get_blueprint_library() - num_peds = min(self.config['traffic']['pedestrians'], 8) spawned = 0 - - for _ in range(num_peds): + for i in range(min(count, 12)): try: ped_bps = list(blueprint_lib.filter('walker.pedestrian.*')) if not ped_bps: @@ -178,8 +274,9 @@ def spawn_pedestrians(self, center_location): ped_bp = random.choice(ped_bps) + # 在中心位置周围生成 angle = random.uniform(0, 2 * math.pi) - distance = random.uniform(5.0, 12.0) + distance = random.uniform(3.0, 15.0) location = carla.Location( x=center_location.x + distance * math.cos(angle), @@ -188,17 +285,83 @@ def spawn_pedestrians(self, center_location): ) pedestrian = self.world.spawn_actor(ped_bp, carla.Transform(location)) - self.pedestrians.append(pedestrian) + + # 尝试添加AI控制器 + try: + controller_bp = blueprint_lib.find('controller.ai.walker') + if controller_bp: + controller = self.world.spawn_actor( + controller_bp, + carla.Transform(), + attach_to=pedestrian + ) + controller.start() + + # 设置随机目标 + target = self.world.get_random_location_from_navigation() + if target: + controller.go_to_location(target) + + self.pedestrians.append((pedestrian, controller)) + else: + self.pedestrians.append((pedestrian, None)) + + except: + self.pedestrians.append((pedestrian, None)) + spawned += 1 + except Exception as e: - Logger.debug(f"行人生成失败: {e}") + Log.debug(f"行人生成失败: {e}") - Logger.info(f"行人: {spawned} 个") return spawned + def add_static_obstacles(self, center_location): + """添加静态障碍物""" + try: + cones = SceneManager.spawn_traffic_cones(self.world, center_location, 6) + barriers = SceneManager.spawn_construction_barriers(self.world, center_location, 3) + + self.static_obstacles.extend(cones) + self.static_obstacles.extend(barriers) + + Log.info(f"添加障碍物: {len(cones)}个锥桶, {len(barriers)}个路障") + + except Exception as e: + Log.warning(f"添加障碍物失败: {e}") + + def setup_accident_scene(self, center_location): + """设置事故场景""" + try: + accidents, emergency = SceneManager.setup_traffic_accident( + self.world, center_location, 'minor' + ) + + self.vehicles.extend(accidents) + self.vehicles.extend(emergency) + + Log.info(f"事故场景: {len(accidents)}辆事故车, {len(emergency)}辆应急车") + + except Exception as e: + Log.warning(f"设置事故场景失败: {e}") + + def update_traffic_flow(self): + """更新交通流""" + # 随机改变一些车辆的速度 + for vehicle in self.vehicles[:10]: # 只处理前10辆车 + try: + if random.random() < 0.01: # 1%概率 + control = vehicle.get_control() + control.throttle *= random.uniform(0.8, 1.2) + vehicle.apply_control(control) + except: + pass + def cleanup(self): - Logger.info("清理交通...") + """清理交通""" + Log.info("清理交通系统...") + # 清理车辆 for vehicle in self.vehicles: try: if vehicle.is_alive: @@ -206,18 +369,33 @@ def cleanup(self): except: pass - for pedestrian in self.pedestrians: + # 清理行人 + for pedestrian, controller in self.pedestrians: try: + if controller and controller.is_alive: + controller.stop() + controller.destroy() if pedestrian.is_alive: pedestrian.destroy() except: pass + # 清理障碍物 + for obstacle in self.static_obstacles: + try: + if obstacle.is_alive: + obstacle.destroy() + except: + pass + self.vehicles.clear() self.pedestrians.clear() + self.static_obstacles.clear() class SensorSystem: + """传感器系统 - 支持多类型传感器""" + def __init__(self, world, config, data_dir): self.world = world self.config = config @@ -231,86 +409,117 @@ def __init__(self, world, config, data_dir): self.infra_buffer = {} self.buffer_lock = threading.Lock() - self.image_stitcher = ImageStitcher(data_dir) + self.image_processor = ImageProcessor(data_dir) + self.annotation_generator = None + # 摄像头配置 self.camera_configs = { 'vehicle': { 'front_wide': {'loc': (2.0, 0, 1.8), 'rot': (0, -3, 0), 'fov': 100}, 'front_narrow': {'loc': (2.0, 0, 1.6), 'rot': (0, 0, 0), 'fov': 60}, 'right_side': {'loc': (0.5, 1.0, 1.5), 'rot': (0, -2, 45), 'fov': 90}, - 'left_side': {'loc': (0.5, -1.0, 1.5), 'rot': (0, -2, -45), 'fov': 90} + 'left_side': {'loc': (0.5, -1.0, 1.5), 'rot': (0, -2, -45), 'fov': 90}, + 'rear': {'loc': (-1.5, 0, 1.5), 'rot': (0, -2, 180), 'fov': 90} }, 'infrastructure': [ - {'name': 'north', 'offset': (0, -20, 12), 'rotation': (0, -25, 180)}, - {'name': 'south', 'offset': (0, 20, 12), 'rotation': (0, -25, 0)}, - {'name': 'east', 'offset': (20, 0, 12), 'rotation': (0, -25, -90)}, - {'name': 'west', 'offset': (-20, 0, 12), 'rotation': (0, -25, 90)} + {'name': 'north', 'loc': (0, -25, 15), 'rot': (0, -25, 180)}, + {'name': 'south', 'loc': (0, 25, 15), 'rot': (0, -25, 0)}, + {'name': 'east', 'loc': (25, 0, 15), 'rot': (0, -25, -90)}, + {'name': 'west', 'loc': (-25, 0, 15), 'rot': (0, -25, 90)}, + {'name': 'top', 'loc': (0, 0, 25), 'rot': (-90, 0, 0)} ] } - def setup_vehicle_cameras(self, vehicle): - if not vehicle: - return 0 + def enable_annotations(self): + """启用自动标注""" + self.annotation_generator = AnnotationGenerator(self.data_dir) + def setup_cameras(self, vehicle, center_location, enable_vehicle=True, enable_infra=True): + """设置摄像头系统""" installed = 0 + + if enable_vehicle and vehicle: + installed += self._setup_vehicle_cameras(vehicle) + + if enable_infra: + installed += self._setup_infrastructure_cameras(center_location) + + Log.info(f"摄像头安装: {installed}个") + return installed + + def _setup_vehicle_cameras(self, vehicle): + """设置车辆摄像头""" + installed = 0 + for cam_name, config_data in self.camera_configs['vehicle'].items(): if self._create_camera(cam_name, config_data, vehicle, 'vehicle'): installed += 1 - Logger.info(f"车辆摄像头: {installed}") return installed - def setup_infrastructure_cameras(self, center_location): + def _setup_infrastructure_cameras(self, center_location): + """设置基础设施摄像头""" installed = 0 for cam_config in self.camera_configs['infrastructure']: sensor_config = { 'loc': ( - center_location.x + cam_config['offset'][0], - center_location.y + cam_config['offset'][1], - center_location.z + cam_config['offset'][2] + center_location.x + cam_config['loc'][0], + center_location.y + cam_config['loc'][1], + center_location.z + cam_config['loc'][2] ), - 'rot': cam_config['rotation'], + 'rot': cam_config['rot'], 'fov': 90 } if self._create_camera(cam_config['name'], sensor_config, None, 'infrastructure'): installed += 1 - Logger.info(f"基础设施摄像头: {installed}") return installed def _create_camera(self, name, config, parent, sensor_type): + """创建摄像头""" try: blueprint = self.world.get_blueprint_library().find('sensor.camera.rgb') - blueprint.set_attribute('image_size_x', '1280') - blueprint.set_attribute('image_size_y', '720') + + # 设置摄像头参数 + img_size = self.config['sensors'].get('image_size', [1280, 720]) + blueprint.set_attribute('image_size_x', str(img_size[0])) + blueprint.set_attribute('image_size_y', str(img_size[1])) blueprint.set_attribute('fov', str(config.get('fov', 90))) - location = carla.Location(config['loc'][0], config['loc'][1], config['loc'][2]) - rotation = carla.Rotation(config['rot'][0], config['rot'][1], config['rot'][2]) + # 质量设置 + blueprint.set_attribute('motion_blur_intensity', '0') + blueprint.set_attribute('enable_postprocess_effects', 'False') + + location = carla.Location(*config['loc']) + rotation = carla.Rotation(*config['rot']) transform = carla.Transform(location, rotation) + # 生成摄像头 if parent: camera = self.world.spawn_actor(blueprint, transform, attach_to=parent) else: camera = self.world.spawn_actor(blueprint, transform) + # 创建保存目录 save_dir = os.path.join(self.data_dir, "raw", sensor_type, name) os.makedirs(save_dir, exist_ok=True) - callback = self._create_callback(save_dir, name, sensor_type) + # 设置回调 + callback = self._create_image_callback(save_dir, name, sensor_type) camera.listen(callback) self.sensors.append(camera) return True except Exception as e: - Logger.warning(f"创建摄像头 {name} 失败: {e}") + Log.warning(f"创建摄像头 {name} 失败: {e}") return False - def _create_callback(self, save_dir, name, sensor_type): - capture_interval = self.config['sensors']['capture_interval'] + def _create_image_callback(self, save_dir, name, sensor_type): + """创建图像回调函数""" + capture_interval = self.config['sensors'].get('capture_interval', 2.0) def callback(image): current_time = time.time() @@ -319,28 +528,43 @@ def callback(image): self.frame_counter += 1 self.last_capture_time = current_time + # 保存原始图像 filename = os.path.join(save_dir, f"{name}_{self.frame_counter:06d}.png") image.save_to_disk(filename, carla.ColorConverter.Raw) + # 更新缓冲区 with self.buffer_lock: if sensor_type == 'vehicle': self.vehicle_buffer[name] = filename if len(self.vehicle_buffer) >= 4: - self.image_stitcher.stitch(self.vehicle_buffer, self.frame_counter, 'vehicle') + self.image_processor.stitch_4_view( + self.vehicle_buffer, self.frame_counter, 'vehicle' + ) self.vehicle_buffer.clear() else: self.infra_buffer[name] = filename if len(self.infra_buffer) >= 4: - self.image_stitcher.stitch(self.infra_buffer, self.frame_counter, 'infrastructure') + self.image_processor.stitch_4_view( + self.infra_buffer, self.frame_counter, 'infrastructure' + ) self.infra_buffer.clear() + # 生成标注 + if self.annotation_generator: + timestamp = datetime.now().isoformat() + self.annotation_generator.detect_objects( + self.world, self.frame_counter, timestamp + ) + return callback def get_frame_count(self): + """获取帧数""" return self.frame_counter def cleanup(self): - Logger.info(f"清理 {len(self.sensors)} 个传感器...") + """清理传感器""" + Log.info(f"清理 {len(self.sensors)} 个传感器...") for sensor in self.sensors: try: sensor.stop() @@ -351,6 +575,8 @@ def cleanup(self): class DataCollector: + """数据收集器 - 主控制器""" + def __init__(self, config): self.config = config self.client = None @@ -360,13 +586,22 @@ def __init__(self, config): self.setup_directories() - self.traffic_system = None + self.traffic_manager = None self.sensor_system = None self.start_time = None self.is_running = False + self.collected_frames = 0 + + # 性能监控 + self.performance_stats = { + 'fps_history': [], + 'memory_usage': [], + 'start_time': 0 + } def setup_directories(self): + """设置目录结构""" scenario = self.config['scenario'] timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") @@ -375,116 +610,215 @@ def setup_directories(self): f"{scenario['name']}_{scenario['town']}_{timestamp}" ) - for subdir in ["raw/vehicle", "raw/infrastructure", "stitched", "metadata"]: + # 创建目录结构 + directories = [ + "raw/vehicle", + "raw/infrastructure", + "stitched", + "annotations", + "metadata", + "calibration", + "logs" + ] + + for subdir in directories: os.makedirs(os.path.join(self.output_dir, subdir), exist_ok=True) - Logger.info(f"数据目录: {self.output_dir}") + Log.info(f"数据目录: {self.output_dir}") def connect(self): + """连接到CARLA服务器""" for attempt in range(1, 6): try: self.client = carla.Client('localhost', 2000) - self.client.set_timeout(10.0) + self.client.set_timeout(15.0) town = self.config['scenario']['town'] self.world = self.client.load_world(town) + # 设置世界参数 settings = self.world.get_settings() settings.synchronous_mode = False + settings.fixed_delta_seconds = 0.05 self.world.apply_settings(settings) - Logger.info(f"连接成功: {town}") + Log.info(f"连接成功: {town}") return True except Exception as e: - Logger.warning(f"连接尝试 {attempt}/5 失败: {str(e)[:50]}") - time.sleep(2) + Log.warning(f"连接尝试 {attempt}/5 失败: {str(e)[:50]}") + if attempt < 5: + time.sleep(3) return False - def setup_scene(self): + def setup_scene(self, scene_type=None, add_obstacles=False, add_accident=False): + """设置场景""" + # 设置天气 weather_cfg = self.config['scenario'] - weather = WeatherManager.create_weather(weather_cfg['weather'], weather_cfg['time_of_day']) + weather = WeatherSystem.create_weather( + weather_cfg['weather'], + weather_cfg['time_of_day'] + ) self.world.set_weather(weather) - Logger.info(f"天气: {weather_cfg['weather']}, 时间: {weather_cfg['time_of_day']}") + Log.info(f"天气: {weather_cfg['weather']}, 时间: {weather_cfg['time_of_day']}") + + # 获取场景中心 spawn_points = self.world.get_map().get_spawn_points() if spawn_points: self.scene_center = spawn_points[len(spawn_points) // 2].location else: self.scene_center = carla.Location(0, 0, 0) - self.traffic_system = TrafficSystem(self.world, self.config) + # 应用场景配置 + if scene_type: + self.config = SceneManager.setup_scene( + self.world, self.config, scene_type + ) + SceneManager.save_scene_description( + self.output_dir, scene_type, self.config + ) + + # 初始化交通管理器 + self.traffic_manager = TrafficManager(self.world, self.config) - self.ego_vehicle = self.traffic_system.spawn_ego_vehicle() + # 生成主车 + self.ego_vehicle = self.traffic_manager.spawn_ego_vehicle() if not self.ego_vehicle: - Logger.error("主车生成失败") + Log.error("主车生成失败") return False - self.traffic_system.spawn_background_vehicles() - self.traffic_system.spawn_pedestrians(self.scene_center) + # 生成交通 + vehicles = self.config['traffic'].get('background_vehicles', 8) + pedestrians = self.config['traffic'].get('pedestrians', 6) + self.traffic_manager.spawn_traffic( + self.scene_center, vehicles, pedestrians + ) + + # 添加障碍物 + if add_obstacles: + self.traffic_manager.add_static_obstacles(self.scene_center) + + # 添加事故场景 + if add_accident: + self.traffic_manager.setup_accident_scene(self.scene_center) + + # 等待场景稳定 + Log.info("等待场景稳定...") + time.sleep(5.0) - time.sleep(2.0) return True - def setup_sensors(self): - self.sensor_system = SensorSystem(self.world, self.config, self.output_dir) + def setup_sensors(self, enable_annotations=True): + """设置传感器""" + self.sensor_system = SensorSystem( + self.world, + self.config, + self.output_dir + ) - vehicle_cams = self.sensor_system.setup_vehicle_cameras(self.ego_vehicle) - infra_cams = self.sensor_system.setup_infrastructure_cameras(self.scene_center) + if enable_annotations: + self.sensor_system.enable_annotations() - total_cams = vehicle_cams + infra_cams - if total_cams == 0: - Logger.error("没有摄像头安装成功") + # 安装摄像头 + vehicle_cams = self.config['sensors'].get('vehicle_cameras', 4) + infra_cams = self.config['sensors'].get('infrastructure_cameras', 4) + + installed = self.sensor_system.setup_cameras( + self.ego_vehicle, + self.scene_center, + vehicle_cams > 0, + infra_cams > 0 + ) + + if installed == 0: + Log.error("没有摄像头安装成功") return False - Logger.info(f"摄像头总数: {total_cams}") + Log.info(f"传感器系统就绪: {installed}个摄像头") return True - def run_collection(self): + def collect_data(self): + """收集数据""" duration = self.config['scenario']['duration'] - Logger.info(f"开始数据收集,时长: {duration}秒") + Log.info(f"开始数据收集,时长: {duration}秒") self.start_time = time.time() self.is_running = True + self.performance_stats['start_time'] = self.start_time last_update = time.time() + last_fps_check = time.time() + frame_counter = 0 try: while time.time() - self.start_time < duration and self.is_running: current_time = time.time() elapsed = current_time - self.start_time + # 更新交通 + if self.traffic_manager: + self.traffic_manager.update_traffic_flow() + + # 性能监控 + if current_time - last_fps_check >= 1.0: + current_frames = self.sensor_system.get_frame_count() + fps = current_frames - frame_counter + self.performance_stats['fps_history'].append(fps) + frame_counter = current_frames + last_fps_check = current_time + + # 进度更新 if current_time - last_update >= 5.0: frames = self.sensor_system.get_frame_count() progress = (elapsed / duration) * 100 + remaining = duration - elapsed + + avg_fps = sum(self.performance_stats['fps_history'][-5:]) / \ + min(len(self.performance_stats['fps_history'][-5:]), 5) - Logger.info(f"进度: {elapsed:.0f}/{duration}秒 ({progress:.1f}%) | 帧数: {frames}") + Log.info( + f"进度: {elapsed:.0f}/{duration}秒 ({progress:.1f}%) | " + f"帧数: {frames} | FPS: {avg_fps:.1f} | " + f"剩余: {remaining:.0f}秒" + ) last_update = current_time - time.sleep(0.05) + time.sleep(0.01) except KeyboardInterrupt: - Logger.info("数据收集被用户中断") + Log.info("数据收集被用户中断") finally: self.is_running = False elapsed = time.time() - self.start_time - frames = self.sensor_system.get_frame_count() if self.sensor_system else 0 - Logger.info(f"收集完成: {frames}帧, 用时: {elapsed:.1f}秒") + self.collected_frames = self.sensor_system.get_frame_count() if self.sensor_system else 0 + Log.info(f"收集完成: {self.collected_frames}帧, 用时: {elapsed:.1f}秒") - self._save_metadata(frames, elapsed) - self._print_summary() + self._save_collection_metadata() + self._generate_dataset_report() - def _save_metadata(self, total_frames, elapsed_time): + def _save_collection_metadata(self): + """保存收集元数据""" metadata = { 'scenario': self.config['scenario'], 'traffic': self.config['traffic'], 'sensors': self.config['sensors'], + 'output': self.config['output'], 'collection': { - 'duration': elapsed_time, - 'total_frames': total_frames, - 'frame_rate': total_frames / elapsed_time if elapsed_time > 0 else 0 + 'start_time': datetime.fromtimestamp(self.start_time).isoformat(), + 'duration_seconds': round(time.time() - self.start_time, 2), + 'total_frames': self.collected_frames, + 'frame_rate': round(self.collected_frames / (time.time() - self.start_time), 2) + }, + 'performance': { + 'average_fps': round( + sum(self.performance_stats['fps_history']) / + max(len(self.performance_stats['fps_history']), 1), + 2 + ), + 'fps_history': self.performance_stats['fps_history'][:20] # 只保留前20个 } } @@ -492,38 +826,85 @@ def _save_metadata(self, total_frames, elapsed_time): with open(meta_path, 'w', encoding='utf-8') as f: json.dump(metadata, f, indent=2, ensure_ascii=False) - Logger.info(f"元数据保存: {meta_path}") + Log.info(f"元数据保存: {meta_path}") - def _print_summary(self): + def _generate_dataset_report(self): + """生成数据集报告""" print("\n" + "=" * 60) - print("数据收集摘要") + print("数据集生成报告") print("=" * 60) + # 基本统计 + total_size = self._get_directory_size(self.output_dir) + print(f"总数据大小: {total_size} MB") + print(f"总帧数: {self.collected_frames}") + + # 文件统计 stitched_dir = os.path.join(self.output_dir, "stitched") if os.path.exists(stitched_dir): - files = [f for f in os.listdir(stitched_dir) if f.endswith('.jpg')] - print(f"拼接图像: {len(files)} 张") + stitched_files = [f for f in os.listdir(stitched_dir) if f.endswith('.jpg')] + print(f"拼接图像: {len(stitched_files)} 张") - raw_dirs = ["vehicle", "infrastructure"] - for raw_dir in raw_dirs: - path = os.path.join(self.output_dir, "raw", raw_dir) - if os.path.exists(path): - total = 0 - for root, dirs, files in os.walk(path): - total += len([f for f in files if f.endswith('.png')]) - print(f"原始图像 ({raw_dir}): {total} 张") + # 原始图像统计 + raw_stats = self._count_raw_images() + print(f"原始图像: {raw_stats['total']} 张") + print(f" 车辆视角: {raw_stats['vehicle']} 张") + print(f" 基础设施: {raw_stats['infrastructure']} 张") + + # 标注统计 + annotations_dir = os.path.join(self.output_dir, "annotations") + if os.path.exists(annotations_dir): + json_files = [f for f in os.listdir(annotations_dir) if f.endswith('.json')] + print(f"标注文件: {len(json_files)} 个") print(f"\n输出目录: {self.output_dir}") print("=" * 60) + def _count_raw_images(self): + """统计原始图像""" + stats = {'total': 0, 'vehicle': 0, 'infrastructure': 0} + + for view_type in ['vehicle', 'infrastructure']: + path = os.path.join(self.output_dir, "raw", view_type) + if os.path.exists(path): + count = 0 + for root, dirs, files in os.walk(path): + count += len([f for f in files if f.endswith('.png')]) + + stats[view_type] = count + stats['total'] += count + + return stats + + def _get_directory_size(self, path): + """计算目录大小""" + total = 0 + for dirpath, dirnames, filenames in os.walk(path): + for f in filenames: + fp = os.path.join(dirpath, f) + if os.path.exists(fp): + total += os.path.getsize(fp) + return round(total / (1024 * 1024), 2) + + def run_analysis(self): + """运行数据集分析""" + Log.info("运行数据集分析...") + DataAnalyzer.analyze_dataset(self.output_dir) + + def run_validation(self): + """运行数据验证""" + Log.info("运行数据验证...") + DataValidator.validate_dataset(self.output_dir) + def cleanup(self): - Logger.info("清理场景...") + """清理场景""" + Log.info("清理场景...") if self.sensor_system: self.sensor_system.cleanup() - if self.traffic_system: - self.traffic_system.cleanup() + if self.traffic_manager: + self.traffic_manager.cleanup() if self.ego_vehicle and self.ego_vehicle.is_alive: try: @@ -531,41 +912,55 @@ def cleanup(self): except: pass - Logger.info("清理完成") - - # 运行数据验证 - if self.config['output'].get('validate_data', True): - DataValidator.validate_dataset(self.output_dir) + Log.info("清理完成") def main(): - parser = argparse.ArgumentParser(description='CVIPS 数据收集系统') + """主函数""" + parser = argparse.ArgumentParser(description='CVIPS 高级交通场景数据集生成器') + # 基础参数 parser.add_argument('--config', type=str, help='配置文件路径') parser.add_argument('--scenario', type=str, default='urban_scene', help='场景名称') parser.add_argument('--town', type=str, default='Town10HD', choices=['Town03', 'Town04', 'Town05', 'Town10HD'], help='地图') parser.add_argument('--weather', type=str, default='clear', - choices=['clear', 'rainy', 'cloudy'], help='天气') + choices=['clear', 'rainy', 'cloudy', 'foggy', 'stormy'], help='天气') parser.add_argument('--time-of-day', type=str, default='noon', - choices=['noon', 'sunset', 'night'], help='时间') + choices=['noon', 'sunset', 'night', 'morning', 'dawn'], help='时间') + + # 交通参数 parser.add_argument('--num-vehicles', type=int, default=8, help='背景车辆数') - parser.add_argument('--num-pedestrians', type=int, default=10, help='行人数') + parser.add_argument('--num-pedestrians', type=int, default=6, help='行人数') + parser.add_argument('--ego-vehicle', type=str, help='主车类型') + + # 收集参数 parser.add_argument('--duration', type=int, default=60, help='收集时长(秒)') parser.add_argument('--capture-interval', type=float, default=2.0, help='捕捉间隔(秒)') parser.add_argument('--seed', type=int, help='随机种子') - parser.add_argument('--validate-data', action='store_true', help='启用数据验证') + + # 场景参数 + parser.add_argument('--scene-type', type=str, + choices=['intersection_4way', 'highway', 'urban_street', + 'night_scene', 'rainy_intersection'], help='场景类型') + parser.add_argument('--add-obstacles', action='store_true', help='添加障碍物') + parser.add_argument('--add-accident', action='store_true', help='添加事故场景') + + # 功能参数 + parser.add_argument('--enable-annotations', action='store_true', help='启用自动标注') + parser.add_argument('--run-analysis', action='store_true', help='运行数据集分析') + parser.add_argument('--run-validation', action='store_true', help='运行数据验证') + parser.add_argument('--skip-validation', action='store_true', help='跳过数据验证') args = parser.parse_args(remaining_argv) + # 加载配置 config = ConfigManager.load_config(args.config) config = ConfigManager.merge_args(config, args) - if args.validate_data: - config['output']['validate_data'] = True - + # 显示配置 print("\n" + "=" * 60) - print("CVIPS 数据收集系统") + print("CVIPS 交通场景数据集生成器 v8.0") print("=" * 60) print(f"场景: {config['scenario']['name']}") @@ -573,26 +968,53 @@ def main(): print(f"天气/时间: {config['scenario']['weather']}/{config['scenario']['time_of_day']}") print(f"时长: {config['scenario']['duration']}秒") print(f"交通: {config['traffic']['background_vehicles']}车辆 + {config['traffic']['pedestrians']}行人") - print(f"验证: {'启用' if config['output'].get('validate_data', True) else '禁用'}") + if args.scene_type: + print(f"场景类型: {args.scene_type}") + if args.add_obstacles: + print(f"障碍物: 启用") + if args.add_accident: + print(f"事故场景: 启用") + + print(f"标注: {'启用' if args.enable_annotations else '禁用'}") + print(f"分析: {'启用' if args.run_analysis else '禁用'}") + print(f"验证: {'禁用' if args.skip_validation else '启用'}") + + # 创建收集器 collector = DataCollector(config) try: + # 连接服务器 if not collector.connect(): print("连接CARLA服务器失败") return - if not collector.setup_scene(): + # 设置场景 + if not collector.setup_scene( + args.scene_type, + args.add_obstacles, + args.add_accident + ): print("场景设置失败") collector.cleanup() return - if not collector.setup_sensors(): + # 设置传感器 + if not collector.setup_sensors(args.enable_annotations): print("传感器设置失败") collector.cleanup() return - collector.run_collection() + # 收集数据 + collector.collect_data() + + # 运行分析 + if args.run_analysis: + collector.run_analysis() + + # 运行验证 + if not args.skip_validation: + collector.run_validation() except KeyboardInterrupt: print("\n程序被用户中断") diff --git a/src/enhance_pedestrian_safety/scene_manager.py b/src/enhance_pedestrian_safety/scene_manager.py new file mode 100644 index 0000000000..dbe424d7d4 --- /dev/null +++ b/src/enhance_pedestrian_safety/scene_manager.py @@ -0,0 +1,245 @@ +import os +import json +import random +import math +import carla + + +class SceneManager: + """场景管理器 - 支持多种预定义场景""" + + # 场景预设配置 + SCENES = { + 'intersection_4way': { + 'description': '四路交叉口场景', + 'pedestrian_behavior': ['crossing', 'walking'], + 'vehicle_density': 0.7, + 'pedestrian_density': 0.8, + 'weather_variations': ['clear', 'cloudy'] + }, + 'highway': { + 'description': '高速公路场景', + 'pedestrian_behavior': [], + 'vehicle_density': 0.9, + 'pedestrian_density': 0.0, + 'weather_variations': ['clear', 'rainy'] + }, + 'urban_street': { + 'description': '城市街道场景', + 'pedestrian_behavior': ['walking', 'crossing', 'waiting'], + 'vehicle_density': 0.6, + 'pedestrian_density': 0.7, + 'weather_variations': ['clear', 'cloudy', 'rainy'] + }, + 'night_scene': { + 'description': '夜间场景', + 'pedestrian_behavior': ['walking'], + 'vehicle_density': 0.5, + 'pedestrian_density': 0.4, + 'weather_variations': ['clear'], + 'time_of_day': 'night' + }, + 'rainy_intersection': { + 'description': '雨天交叉口', + 'pedestrian_behavior': ['crossing'], + 'vehicle_density': 0.6, + 'pedestrian_density': 0.5, + 'weather_variations': ['rainy'] + } + } + + @staticmethod + def setup_scene(world, config, scene_type='intersection_4way'): + """设置特定场景""" + if scene_type not in SceneManager.SCENES: + print(f"未知场景类型: {scene_type}") + return config + + scene_config = SceneManager.SCENES[scene_type] + + # 更新配置 + if 'time_of_day' in scene_config: + config['scenario']['time_of_day'] = scene_config['time_of_day'] + + if scene_config['weather_variations']: + config['scenario']['weather'] = random.choice(scene_config['weather_variations']) + + # 调整交通密度 + base_vehicles = config['traffic']['background_vehicles'] + base_pedestrians = config['traffic']['pedestrians'] + + config['traffic']['background_vehicles'] = int(base_vehicles * scene_config['vehicle_density']) + config['traffic']['pedestrians'] = int(base_pedestrians * scene_config['pedestrian_density']) + + # 设置行人行为 + config['traffic']['pedestrian_behaviors'] = scene_config['pedestrian_behavior'] + + # 应用场景特定设置 + SceneManager._apply_scene_specifics(world, scene_type) + + return config + + @staticmethod + def _apply_scene_specifics(world, scene_type): + """应用场景特定的设置""" + try: + if scene_type == 'highway': + # 高速公路场景:设置较高车速 + for actor in world.get_actors(): + if 'vehicle' in actor.type_id: + try: + actor.enable_constant_velocity(carla.Vector3D(25, 0, 0)) + except: + pass + + elif scene_type == 'night_scene': + # 夜间场景:调整灯光 + for actor in world.get_actors(): + if 'vehicle' in actor.type_id: + try: + light_state = carla.VehicleLightState.Position | carla.VehicleLightState.LowBeam + actor.set_light_state(light_state) + except: + pass + + except Exception as e: + print(f"场景特定设置失败: {e}") + + @staticmethod + def spawn_traffic_cones(world, center_location, num_cones=10): + """生成交通锥桶""" + blueprint_lib = world.get_blueprint_library() + cone_bp = blueprint_lib.find('static.prop.roadcone') + + cones = [] + for i in range(num_cones): + try: + angle = random.uniform(0, 2 * math.pi) + distance = random.uniform(3.0, 8.0) + + location = carla.Location( + x=center_location.x + distance * math.cos(angle), + y=center_location.y + distance * math.sin(angle), + z=center_location.z + 0.2 + ) + + rotation = carla.Rotation(0, random.uniform(0, 360), 0) + transform = carla.Transform(location, rotation) + + cone = world.spawn_actor(cone_bp, transform) + cones.append(cone) + + except Exception as e: + print(f"生成交通锥桶失败: {e}") + + return cones + + @staticmethod + def spawn_construction_barriers(world, center_location, num_barriers=5): + """生成施工障碍物""" + blueprint_lib = world.get_blueprint_library() + barrier_bp = blueprint_lib.find('static.prop.constructionbarrier') + + barriers = [] + for i in range(num_barriers): + try: + angle = random.uniform(0, 2 * math.pi) + distance = random.uniform(5.0, 12.0) + + location = carla.Location( + x=center_location.x + distance * math.cos(angle), + y=center_location.y + distance * math.sin(angle), + z=center_location.z + 0.2 + ) + + rotation = carla.Rotation(0, random.uniform(0, 360), 0) + transform = carla.Transform(location, rotation) + + barrier = world.spawn_actor(barrier_bp, transform) + barriers.append(barrier) + + except Exception as e: + print(f"生成施工障碍物失败: {e}") + + return barriers + + @staticmethod + def setup_traffic_accident(world, center_location, severity='minor'): + """设置交通事故场景""" + blueprint_lib = world.get_blueprint_library() + + # 生成事故车辆 + accident_vehicles = [] + for i in range(2): # 两车事故 + try: + vehicle_bp = random.choice(list(blueprint_lib.filter('vehicle.*'))) + + # 稍微偏移位置,模拟碰撞 + offset_x = random.uniform(-3.0, 3.0) if i == 0 else random.uniform(2.0, 5.0) + offset_y = random.uniform(-2.0, 2.0) if i == 0 else random.uniform(-5.0, -2.0) + + location = carla.Location( + x=center_location.x + offset_x, + y=center_location.y + offset_y, + z=center_location.z + 0.5 + ) + + # 设置碰撞角度 + rotation = carla.Rotation( + 0, + random.uniform(-30, 30) + (90 if i == 1 else 0), + 0 + ) + + transform = carla.Transform(location, rotation) + vehicle = world.spawn_actor(vehicle_bp, transform) + + # 根据严重程度设置车辆损坏 + if severity == 'major': + vehicle.set_light_state(carla.VehicleLightState.Hazard) + + accident_vehicles.append(vehicle) + + except Exception as e: + print(f"生成事故车辆失败: {e}") + + # 生成应急车辆(警车、救护车) + emergency_vehicles = [] + try: + police_bp = blueprint_lib.find('vehicle.dodge.charger_police') + if police_bp: + location = carla.Location( + x=center_location.x - 8.0, + y=center_location.y + 4.0, + z=center_location.z + 0.5 + ) + rotation = carla.Rotation(0, 45, 0) + police = world.spawn_actor(police_bp, carla.Transform(location, rotation)) + police.set_light_state(carla.VehicleLightState.Special1) + emergency_vehicles.append(police) + except: + pass + + return accident_vehicles, emergency_vehicles + + @staticmethod + def save_scene_description(output_dir, scene_type, config, extra_info=None): + """保存场景描述文件""" + scene_info = { + 'scene_type': scene_type, + 'description': SceneManager.SCENES.get(scene_type, {}).get('description', '未知场景'), + 'config': config, + 'created': SceneManager._get_timestamp(), + 'extra_info': extra_info or {} + } + + scene_file = os.path.join(output_dir, "metadata", "scene_description.json") + with open(scene_file, 'w', encoding='utf-8') as f: + json.dump(scene_info, f, indent=2, ensure_ascii=False) + + print(f"场景描述保存: {scene_file}") + + @staticmethod + def _get_timestamp(): + from datetime import datetime + return datetime.now().isoformat() \ No newline at end of file