diff --git a/src/lane_identification/software package/config.py b/src/lane_identification/software package/config.py deleted file mode 100644 index 521d7aff41..0000000000 --- a/src/lane_identification/software package/config.py +++ /dev/null @@ -1,140 +0,0 @@ -""" -配置管理模块 - 集中管理所有系统参数 -""" - -from dataclasses import dataclass -from typing import Tuple, List -import json -import os - -@dataclass -class AppConfig: - """应用配置参数""" - # 性能参数 - max_image_size: Tuple[int, int] = (1200, 800) - cache_size: int = 8 - batch_size: int = 30 - - # 图像处理参数 - adaptive_clip_limit: float = 2.5 - adaptive_grid_size: Tuple[int, int] = (8, 8) - gaussian_kernel: Tuple[int, int] = (5, 5) - - # 检测参数 - canny_threshold1: int = 50 - canny_threshold2: int = 150 - hough_threshold: int = 30 - hough_min_length: int = 25 - hough_max_gap: int = 40 - min_contour_area: float = 0.005 - - # 方向分析参数 - deviation_threshold: float = 0.15 - width_ratio_threshold: float = 0.7 - confidence_threshold: float = 0.6 - - # 路径预测参数 - prediction_steps: int = 10 - prediction_distance: float = 0.75 - min_prediction_points: int = 4 - - # 置信度参数 - min_confidence_for_direction: float = 0.4 - confidence_smoothing_factor: float = 0.7 - quality_weight_lane: float = 0.5 - quality_weight_road: float = 0.3 - quality_weight_consistency: float = 0.2 - - # 界面参数 - ui_refresh_rate: int = 100 - animation_duration: int = 300 - - # 车道线检测参数 - lane_detection_methods: List[str] = None - - def __post_init__(self): - if self.lane_detection_methods is None: - self.lane_detection_methods = ['canny', 'sobel', 'gradient'] - - def to_dict(self) -> dict: - """转换为字典""" - return { - 'max_image_size': self.max_image_size, - 'cache_size': self.cache_size, - 'batch_size': self.batch_size, - 'adaptive_clip_limit': self.adaptive_clip_limit, - 'adaptive_grid_size': self.adaptive_grid_size, - 'canny_threshold1': self.canny_threshold1, - 'canny_threshold2': self.canny_threshold2, - 'hough_threshold': self.hough_threshold, - 'confidence_threshold': self.confidence_threshold, - 'prediction_steps': self.prediction_steps, - 'prediction_distance': self.prediction_distance - } - - def save(self, filepath: str): - """保存配置到文件""" - with open(filepath, 'w') as f: - json.dump(self.to_dict(), f, indent=2) - - @classmethod - def load(cls, filepath: str) -> 'AppConfig': - """从文件加载配置""" - if os.path.exists(filepath): - with open(filepath, 'r') as f: - data = json.load(f) - - # 从字典创建配置对象 - config = cls() - for key, value in data.items(): - if hasattr(config, key): - setattr(config, key, value) - return config - else: - return cls() - - -class SceneConfig: - """场景特定配置""" - - # 高速公路配置 - HIGHWAY = AppConfig( - adaptive_clip_limit=2.0, - canny_threshold1=60, - canny_threshold2=180, - hough_threshold=35, - prediction_distance=0.9, - confidence_threshold=0.7 - ) - - # 城市道路配置 - URBAN = AppConfig( - adaptive_clip_limit=1.5, - canny_threshold1=40, - canny_threshold2=120, - hough_threshold=25, - prediction_distance=0.6, - confidence_threshold=0.5 - ) - - # 乡村道路配置 - RURAL = AppConfig( - adaptive_clip_limit=3.0, - adaptive_grid_size=(16, 16), - canny_threshold1=30, - canny_threshold2=90, - hough_threshold=20, - min_contour_area=0.002, - prediction_distance=0.7, - confidence_threshold=0.4 - ) - - @classmethod - def get_scene_config(cls, scene_type: str) -> AppConfig: - """获取场景特定配置""" - config_map = { - 'highway': cls.HIGHWAY, - 'urban': cls.URBAN, - 'rural': cls.RURAL - } - return config_map.get(scene_type, AppConfig()) \ No newline at end of file diff --git a/src/lane_identification/software package/direction_analyzer.py b/src/lane_identification/software package/direction_analyzer.py deleted file mode 100644 index 86de66b69d..0000000000 --- a/src/lane_identification/software package/direction_analyzer.py +++ /dev/null @@ -1,449 +0,0 @@ -""" -方向分析模块 - 负责分析道路方向并计算置信度 -""" - -import numpy as np -from collections import deque, defaultdict -from typing import Dict, Any, Tuple, List -from config import AppConfig - -class DirectionAnalyzer: - """方向分析器""" - - def __init__(self, config: AppConfig): - self.config = config - self.history = deque(maxlen=10) - - # 特征权重 - self.feature_weights = { - 'lane_convergence': 0.35, - 'lane_symmetry': 0.20, - 'path_curvature': 0.20, - 'contour_position': 0.15, - 'historical_consistency': 0.10 - } - - def analyze(self, road_features: Dict[str, Any], lane_info: Dict[str, Any]) -> Dict[str, Any]: - """分析道路方向""" - try: - # 提取特征 - features = self._extract_features(road_features, lane_info) - - # 方向预测 - direction_probs = self._predict_direction(features) - - # 置信度计算 - confidence = self._calculate_confidence(features, direction_probs, lane_info) - - # 获取最终方向 - final_direction = self._get_final_direction(direction_probs, confidence) - - # 历史平滑 - final_direction, confidence = self._apply_historical_smoothing(final_direction, confidence) - - # 生成推理说明 - reasoning = self._generate_reasoning(features, direction_probs, final_direction) - - # 创建结果 - result = { - 'direction': final_direction, - 'confidence': confidence, - 'probabilities': direction_probs, - 'features': features, - 'reasoning': reasoning - } - - # 更新历史 - if confidence > 0.3: - self.history.append(result) - - return result - - except Exception as e: - print(f"方向分析失败: {e}") - return self._create_default_result() - - def _extract_features(self, road_features: Dict[str, Any], lane_info: Dict[str, Any]) -> Dict[str, Any]: - """提取特征""" - features = {} - - # 1. 轮廓质心特征 - if 'centroid' in road_features: - cx, cy = road_features['centroid'] - features['contour_centroid_x'] = cx - - # 2. 车道线特征 - if lane_info['left_lane'] and lane_info['right_lane']: - features['lane_convergence'] = self._calculate_lane_convergence(lane_info) - features['lane_symmetry'] = self._calculate_lane_symmetry(lane_info) - features['lane_width'] = self._calculate_lane_width(lane_info) - - # 3. 路径特征 - if lane_info['future_path']: - features['path_curvature'] = self._calculate_path_curvature(lane_info['future_path']) - features['path_straightness'] = self._calculate_path_straightness(lane_info['future_path']) - - # 4. 历史特征 - if self.history: - features['historical_consistency'] = self._calculate_historical_consistency() - - # 5. 检测质量 - features['detection_quality'] = lane_info.get('detection_quality', 0.0) - - return features - - def _calculate_lane_convergence(self, lane_info: Dict[str, Any]) -> float: - """计算车道线收敛度""" - left_func = lane_info['left_lane']['func'] - right_func = lane_info['right_lane']['func'] - - # 在顶部和底部计算宽度 - y_bottom = 600 # 假设图像高度 - y_top = int(y_bottom * 0.4) - - width_bottom = right_func(y_bottom) - left_func(y_bottom) - width_top = right_func(y_top) - left_func(y_top) - - if width_bottom > 0: - return float(width_top / width_bottom) - - return 1.0 - - def _calculate_lane_symmetry(self, lane_info: Dict[str, Any]) -> float: - """计算车道对称性""" - left_func = lane_info['left_lane']['func'] - right_func = lane_info['right_lane']['func'] - - def center_func(y): - return (left_func(y) + right_func(y)) / 2 - - y_values = np.linspace(600 * 0.4, 600, 5) - symmetry_scores = [] - - for y in y_values: - center = center_func(y) - left_dist = center - left_func(y) - right_dist = right_func(y) - center - - if left_dist + right_dist > 0: - symmetry = 1 - abs(left_dist - right_dist) / (left_dist + right_dist) - symmetry_scores.append(symmetry) - - return float(np.mean(symmetry_scores) if symmetry_scores else 0.5) - - def _calculate_lane_width(self, lane_info: Dict[str, Any]) -> float: - """计算平均车道宽度""" - left_func = lane_info['left_lane']['func'] - right_func = lane_info['right_lane']['func'] - - y_values = np.linspace(600 * 0.4, 600, 5) - widths = [right_func(y) - left_func(y) for y in y_values] - - return float(np.mean(widths)) - - def _calculate_path_curvature(self, future_path: Dict[str, Any]) -> float: - """计算路径曲率""" - path_points = future_path.get('center_path', []) - - if len(path_points) < 3: - return 0.0 - - pts = np.array(path_points, dtype=np.float32) - x = pts[:, 0] - y = pts[:, 1] - - # 计算导数 - dx = np.gradient(x) - dy = np.gradient(y) - d2x = np.gradient(dx) - d2y = np.gradient(dy) - - # 计算曲率 - curvature = np.abs(dx * d2y - d2x * dy) / (dx**2 + dy**2)**1.5 - - # 返回平均曲率 - return float(np.mean(curvature[np.isfinite(curvature)])) - - def _calculate_path_straightness(self, future_path: Dict[str, Any]) -> float: - """计算路径直线度""" - path_points = future_path.get('center_path', []) - - if len(path_points) < 2: - return 1.0 - - pts = np.array(path_points, dtype=np.float32) - x = pts[:, 0] - y = pts[:, 1] - - # 线性拟合 - coeffs = np.polyfit(y, x, 1) - poly_func = np.poly1d(coeffs) - - # 计算R²值 - residuals = x - poly_func(y) - ss_res = np.sum(residuals**2) - ss_tot = np.sum((x - np.mean(x))**2) - - if ss_tot > 0: - return float(1 - (ss_res / ss_tot)) - - return 0.5 - - def _calculate_historical_consistency(self) -> float: - """计算历史一致性""" - if len(self.history) < 2: - return 0.5 - - recent_directions = [h['direction'] for h in list(self.history)[-3:]] - - if len(recent_directions) >= 2: - from collections import Counter - freq = Counter(recent_directions) - most_common_count = max(freq.values()) - return most_common_count / len(recent_directions) - - return 0.5 - - def _predict_direction(self, features: Dict[str, Any]) -> Dict[str, float]: - """预测方向概率""" - # 基础概率 - probabilities = {'直行': 0.3, '左转': 0.35, '右转': 0.35} - - # 1. 基于轮廓质心 - if 'contour_centroid_x' in features: - centroid_x = features['contour_centroid_x'] - deviation = (centroid_x - 400) / 400 # 归一化到[-1, 1] - - if abs(deviation) < 0.1: - probabilities['直行'] += 0.3 - elif deviation > 0.1: - probabilities['右转'] += abs(deviation) * 0.5 - else: - probabilities['左转'] += abs(deviation) * 0.5 - - # 2. 基于车道线收敛 - if 'lane_convergence' in features: - convergence = features['lane_convergence'] - - if convergence < 0.6: # 明显收敛 - symmetry = features.get('lane_symmetry', 0.5) - if symmetry < 0.6: - probabilities['左转'] += 0.2 - else: - probabilities['右转'] += 0.2 - else: - probabilities['直行'] += 0.2 - - # 3. 基于路径曲率 - if 'path_curvature' in features: - curvature = features['path_curvature'] - - if abs(curvature) < 0.001: - probabilities['直行'] += 0.2 - elif curvature > 0: - probabilities['右转'] += min(0.3, curvature * 100) - else: - probabilities['左转'] += min(0.3, abs(curvature) * 100) - - # 归一化 - total = sum(probabilities.values()) - if total > 0: - for direction in probabilities: - probabilities[direction] /= total - - return probabilities - - def _calculate_confidence(self, features: Dict[str, Any], - probabilities: Dict[str, float], - lane_info: Dict[str, Any]) -> float: - """计算置信度""" - confidence_factors = [] - - # 1. 概率清晰度 - max_prob = max(probabilities.values()) - min_prob = min(probabilities.values()) - if max_prob > 0: - clarity = (max_prob - min_prob) / max_prob - confidence_factors.append(clarity * 0.4) - - # 2. 特征质量 - feature_quality = 0.0 - quality_indicators = [] - - if 'lane_convergence' in features: - convergence = features['lane_convergence'] - conv_confidence = 1 - min(1.0, abs(convergence - 1.0) * 1.5) - quality_indicators.append(conv_confidence) - - if 'lane_symmetry' in features: - symmetry = features['lane_symmetry'] - quality_indicators.append(symmetry) - - if 'path_curvature' in features: - curvature = features['path_curvature'] - curv_confidence = 1 - min(1.0, abs(curvature) * 100) - quality_indicators.append(curv_confidence) - - if quality_indicators: - feature_quality = np.mean(quality_indicators) - - confidence_factors.append(feature_quality * 0.3) - - # 3. 检测质量 - detection_quality = lane_info.get('detection_quality', 0.5) - confidence_factors.append(detection_quality * 0.2) - - # 4. 历史一致性 - if 'historical_consistency' in features: - consistency = features['historical_consistency'] - confidence_factors.append(consistency * 0.1) - - # 综合置信度 - confidence = sum(confidence_factors) - - # 非线性调整 - if confidence < 0.3: - confidence = confidence * 0.8 - elif confidence < 0.7: - confidence = 0.3 + (confidence - 0.3) * 1.1 - - return min(max(confidence, 0.0), 1.0) - - def _get_final_direction(self, probabilities: Dict[str, float], - confidence: float) -> str: - """获取最终方向""" - # 按概率排序 - sorted_directions = sorted(probabilities.items(), key=lambda x: x[1], reverse=True) - - if not sorted_directions: - return '未知' - - best_direction, best_prob = sorted_directions[0] - second_direction, second_prob = sorted_directions[1] if len(sorted_directions) > 1 else ('', 0) - - # 决策逻辑 - if confidence < self.config.min_confidence_for_direction: - return '未知' - elif confidence < self.config.confidence_threshold: - # 需要明显优势 - if best_prob > second_prob * 1.5: - return best_direction - else: - return '未知' - else: - # 允许较小优势 - if best_prob > second_prob * 1.2: - return best_direction - else: - # 参考历史 - if self.history: - historical_direction = self._get_historical_direction() - if historical_direction != '未知': - return historical_direction - - return best_direction - - def _get_historical_direction(self) -> str: - """获取历史主要方向""" - if not self.history: - return '未知' - - recent = list(self.history)[-3:] - direction_counts = defaultdict(int) - - for result in recent: - direction = result.get('direction', '未知') - if direction != '未知': - direction_counts[direction] += 1 - - if not direction_counts: - return '未知' - - return max(direction_counts.items(), key=lambda x: x[1])[0] - - def _apply_historical_smoothing(self, direction: str, confidence: float) -> Tuple[str, float]: - """应用历史平滑""" - if len(self.history) < 2: - return direction, confidence - - recent_history = list(self.history)[-4:] - - # 统计历史方向 - direction_counts = defaultdict(int) - for result in recent_history: - d = result['direction'] - direction_counts[d] += 1 - - if not direction_counts: - return direction, confidence - - most_common, count = max(direction_counts.items(), key=lambda x: x[1]) - frequency = count / len(recent_history) - - # 如果历史一致性高且当前置信度低,信任历史 - if frequency > 0.75 and confidence < 0.5: - historical_confidences = [h.get('confidence', 0) for h in recent_history] - historical_confidence = np.mean(historical_confidences) - return most_common, historical_confidence * 0.9 - - # 如果历史与当前不一致,但历史一致性高 - if most_common != direction and frequency > 0.6: - smoothing_factor = min(0.7, frequency) - historical_confidences = [h.get('confidence', 0) for h in recent_history] - historical_confidence = np.mean(historical_confidences) - - smoothed_confidence = ( - confidence * (1 - smoothing_factor) + - historical_confidence * smoothing_factor - ) - - if confidence < 0.4 and historical_confidence > 0.6: - return most_common, smoothed_confidence - - return direction, confidence - - def _generate_reasoning(self, features: Dict[str, Any], - probabilities: Dict[str, float], - final_direction: str) -> str: - """生成推理说明""" - reasons = [] - - # 基于特征添加原因 - if 'lane_convergence' in features: - convergence = features['lane_convergence'] - if convergence < 0.8: - reasons.append("车道明显收敛") - elif convergence > 1.2: - reasons.append("车道发散") - else: - reasons.append("车道基本平行") - - if 'path_curvature' in features: - curvature = features['path_curvature'] - if abs(curvature) < 0.0005: - reasons.append("路径基本直线") - elif curvature > 0: - reasons.append("路径向右弯曲") - else: - reasons.append("路径向左弯曲") - - # 基于概率添加原因 - sorted_probs = sorted(probabilities.items(), key=lambda x: x[1], reverse=True) - if sorted_probs: - top1, top2 = sorted_probs[:2] - if top1[1] > top2[1] * 1.5: - reasons.append(f"{top1[0]}明显占优") - elif top1[1] > top2[1] * 1.2: - reasons.append(f"{top1[0]}稍占优势") - - return ",".join(reasons) if reasons else "特征不明显" - - def _create_default_result(self) -> Dict[str, Any]: - """创建默认结果""" - return { - 'direction': '未知', - 'confidence': 0.0, - 'probabilities': {'直行': 0.33, '左转': 0.33, '右转': 0.34}, - 'features': {}, - 'reasoning': '检测失败' - } \ No newline at end of file diff --git a/src/lane_identification/software package/image_processor.py b/src/lane_identification/software package/image_processor.py deleted file mode 100644 index 2cee6827ee..0000000000 --- a/src/lane_identification/software package/image_processor.py +++ /dev/null @@ -1,198 +0,0 @@ -""" -图像处理模块 - 负责图像加载、预处理和缓存 -""" - -import cv2 -import numpy as np -from collections import deque -from typing import Optional, Tuple, Dict, Any -import os -from config import AppConfig - -class SmartImageProcessor: - """智能图像处理器""" - - def __init__(self, config: AppConfig): - self.config = config - self._cache = {} - self._cache_order = deque(maxlen=config.cache_size) - - def load_and_preprocess(self, image_path: str) -> Optional[Tuple[np.ndarray, Dict]]: - """加载并预处理图像""" - try: - # 检查缓存 - if image_path in self._cache: - self._cache_order.remove(image_path) - self._cache_order.append(image_path) - return self._cache[image_path] - - # 读取图像 - image = cv2.imread(image_path, cv2.IMREAD_COLOR) - if image is None: - print(f"无法读取图像: {image_path}") - return None - - # 智能调整尺寸 - processed = self._smart_resize(image) - - # 自适应预处理 - processed = self._adaptive_preprocessing(processed) - - # 计算ROI区域 - roi_info = self._calculate_roi(processed.shape) - - # 更新缓存 - result = (processed, roi_info) - self._update_cache(image_path, result) - - return result - - except Exception as e: - print(f"图像处理失败 {image_path}: {e}") - return None - - def _smart_resize(self, image: np.ndarray) -> np.ndarray: - """智能调整图像尺寸""" - height, width = image.shape[:2] - max_w, max_h = self.config.max_image_size - - # 计算最佳缩放比例 - scale_w = max_w / width if width > max_w else 1.0 - scale_h = max_h / height if height > max_h else 1.0 - scale = min(scale_w, scale_h) - - if scale < 1.0: - new_size = (int(width * scale), int(height * scale)) - return cv2.resize(image, new_size, interpolation=cv2.INTER_AREA) - - return image - - def _adaptive_preprocessing(self, image: np.ndarray) -> np.ndarray: - """自适应图像预处理""" - # 转换为YUV颜色空间 - yuv = cv2.cvtColor(image, cv2.COLOR_BGR2YUV) - y_channel = yuv[:, :, 0] - - # 自适应直方图均衡化 - clahe = cv2.createCLAHE( - clipLimit=self.config.adaptive_clip_limit, - tileGridSize=self.config.adaptive_grid_size - ) - yuv[:, :, 0] = clahe.apply(y_channel) - - # 转换回BGR - enhanced = cv2.cvtColor(yuv, cv2.COLOR_YUV2BGR) - - # 自适应去噪 - noise_level = self._estimate_noise_level(y_channel) - if noise_level > 30: - enhanced = cv2.bilateralFilter(enhanced, 9, 75, 75) - - return enhanced - - def _estimate_noise_level(self, image: np.ndarray) -> float: - """估计图像噪声水平""" - laplacian = cv2.Laplacian(image, cv2.CV_64F) - return float(np.std(laplacian)) - - def _calculate_roi(self, image_shape: Tuple[int, ...]) -> Dict[str, Any]: - """计算ROI区域""" - height, width = image_shape[:2] - - # 动态ROI计算 - roi_top = int(height * 0.35) - roi_bottom = int(height * 0.92) - roi_width = int(width * 0.85) - - vertices = np.array([[ - ((width - roi_width) // 2, roi_bottom), - ((width - roi_width) // 2 + int(roi_width * 0.3), roi_top), - ((width - roi_width) // 2 + int(roi_width * 0.7), roi_top), - ((width + roi_width) // 2, roi_bottom) - ]], dtype=np.int32) - - # 创建掩码 - mask = np.zeros(image_shape[:2], dtype=np.uint8) - cv2.fillPoly(mask, vertices, 255) - - return { - 'vertices': vertices, - 'mask': mask, - 'bounds': (roi_top, roi_bottom, roi_width) - } - - def _update_cache(self, key: str, value: Any): - """更新缓存""" - if len(self._cache) >= self.config.cache_size: - oldest = self._cache_order.popleft() - self._cache.pop(oldest, None) - - self._cache[key] = value - self._cache_order.append(key) - - def clear_cache(self): - """清空缓存""" - self._cache.clear() - self._cache_order.clear() - - -class RoadDetector: - """道路检测器""" - - def __init__(self, config: AppConfig): - self.config = config - - def detect_road(self, image: np.ndarray, roi_mask: np.ndarray) -> Dict[str, Any]: - """检测道路区域""" - try: - # 应用ROI - roi_region = cv2.bitwise_and(image, image, mask=roi_mask) - - # 转换为灰度图 - gray = cv2.cvtColor(roi_region, cv2.COLOR_BGR2GRAY) - - # 自适应阈值 - _, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) - - # 形态学操作 - kernel = np.ones((5, 5), np.uint8) - binary = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel) - binary = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel) - - # 查找轮廓 - contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) - - if not contours: - return {'contour': None, 'confidence': 0.0} - - # 找到最大轮廓 - main_contour = max(contours, key=cv2.contourArea) - area = cv2.contourArea(main_contour) - - # 计算凸包和坚实度 - hull = cv2.convexHull(main_contour) - hull_area = cv2.contourArea(hull) - solidity = area / hull_area if hull_area > 0 else 0 - - # 计算质心 - M = cv2.moments(main_contour) - if M["m00"] != 0: - cx = int(M["m10"] / M["m00"]) - cy = int(M["m01"] / M["m00"]) - else: - cx, cy = 0, 0 - - # 计算置信度 - confidence = min(1.0, area / (roi_mask.shape[0] * roi_mask.shape[1]) * 2) - - return { - 'contour': main_contour, - 'centroid': (cx, cy), - 'area': area, - 'solidity': solidity, - 'confidence': confidence - } - - except Exception as e: - print(f"道路检测失败: {e}") - return {'contour': None, 'confidence': 0.0} \ No newline at end of file diff --git a/src/lane_identification/software package/lane_detector.py b/src/lane_identification/software package/lane_detector.py deleted file mode 100644 index c84870aa8f..0000000000 --- a/src/lane_identification/software package/lane_detector.py +++ /dev/null @@ -1,386 +0,0 @@ -""" -车道线检测模块 - 负责检测和拟合车道线 -""" - -import cv2 -import numpy as np -from collections import deque -from typing import Optional, Tuple, List, Dict, Any -from config import AppConfig - -class LaneDetector: - """车道线检测器""" - - def __init__(self, config: AppConfig): - self.config = config - self.lane_history = deque(maxlen=5) - - def detect(self, image: np.ndarray, roi_mask: np.ndarray) -> Dict[str, Any]: - """检测车道线""" - try: - # 预处理 - processed = self._preprocess_for_lanes(image, roi_mask) - - # 边缘检测 - edges = self._detect_edges(processed) - - # 霍夫变换检测直线 - lines = self._hough_transform(edges) - - if lines is None or len(lines) == 0: - return self._create_empty_result() - - # 分类和过滤车道线 - left_lines, right_lines = self._classify_and_filter(lines, image.shape[1]) - - # 拟合车道线 - left_lane = self._fit_lane_model(left_lines, image.shape) - right_lane = self._fit_lane_model(right_lines, image.shape) - - # 验证车道线 - left_lane, right_lane = self._validate_lanes(left_lane, right_lane, image.shape) - - # 计算中心线 - center_line = self._calculate_center_line(left_lane, right_lane, image.shape) - - # 预测路径 - future_path = self._predict_future_path(left_lane, right_lane, image.shape) - - # 计算检测质量 - detection_quality = self._calculate_detection_quality(left_lane, right_lane) - - # 创建结果 - result = { - 'left_lines': left_lines, - 'right_lines': right_lines, - 'left_lane': left_lane, - 'right_lane': right_lane, - 'center_line': center_line, - 'future_path': future_path, - 'detection_quality': detection_quality - } - - # 时间平滑 - result = self._apply_temporal_smoothing(result) - - return result - - except Exception as e: - print(f"车道线检测失败: {e}") - return self._create_empty_result() - - def _preprocess_for_lanes(self, image: np.ndarray, roi_mask: np.ndarray) -> np.ndarray: - """为车道线检测预处理图像""" - # 转换为灰度图 - gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) - - # 应用ROI - gray = cv2.bitwise_and(gray, gray, mask=roi_mask) - - # 自适应直方图均衡化 - clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)) - enhanced = clahe.apply(gray) - - return enhanced - - def _detect_edges(self, image: np.ndarray) -> np.ndarray: - """边缘检测""" - # 自适应Canny阈值 - median = np.median(image) - sigma = 0.33 - lower = int(max(0, (1.0 - sigma) * median)) - upper = int(min(255, (1.0 + sigma) * median)) - - return cv2.Canny(image, lower, upper) - - def _hough_transform(self, edges: np.ndarray) -> Optional[np.ndarray]: - """霍夫变换检测直线""" - lines = cv2.HoughLinesP( - edges, - rho=1, - theta=np.pi/180, - threshold=self.config.hough_threshold, - minLineLength=self.config.hough_min_length, - maxLineGap=self.config.hough_max_gap - ) - return lines - - def _classify_and_filter(self, lines: np.ndarray, image_width: int) -> Tuple[List, List]: - """分类和过滤车道线""" - left_lines, right_lines = [], [] - - for line in lines: - x1, y1, x2, y2 = line[0] - - if x2 == x1: - continue # 跳过垂直线 - - dx = x2 - x1 - dy = y2 - y1 - slope = dy / dx - length = np.sqrt(dx**2 + dy**2) - - # 过滤条件 - if abs(slope) < 0.3 or length < 20: - continue - - midpoint_x = (x1 + x2) / 2 - - # 分类 - if slope < 0: # 左车道线 - if midpoint_x < image_width * 0.6: - left_lines.append({ - 'points': [(x1, y1), (x2, y2)], - 'slope': slope, - 'length': length, - 'midpoint': (midpoint_x, (y1 + y2) / 2) - }) - else: # 右车道线 - if midpoint_x > image_width * 0.4: - right_lines.append({ - 'points': [(x1, y1), (x2, y2)], - 'slope': slope, - 'length': length, - 'midpoint': (midpoint_x, (y1 + y2) / 2) - }) - - return left_lines, right_lines - - def _fit_lane_model(self, lines: List[Dict], image_shape: Tuple[int, ...]) -> Optional[Dict]: - """拟合车道线模型""" - if len(lines) < 2: - return None - - # 收集所有点 - x_points, y_points = [], [] - for line in lines: - for (x, y) in line['points']: - x_points.append(x) - y_points.append(y) - - # 多项式拟合 - try: - coeffs = np.polyfit(y_points, x_points, 2) - model_type = 'quadratic' - except: - coeffs = np.polyfit(y_points, x_points, 1) - model_type = 'linear' - - poly_func = np.poly1d(coeffs) - - # 生成车道线点 - height, width = image_shape[:2] - y_bottom = height - y_top = int(height * 0.4) - - x_bottom = int(poly_func(y_bottom)) - x_top = int(poly_func(y_top)) - - # 限制范围 - x_bottom = max(0, min(width, x_bottom)) - x_top = max(0, min(width, x_top)) - - # 计算置信度 - confidence = min(len(lines) / 10.0, 1.0) - - return { - 'func': poly_func, - 'coeffs': coeffs.tolist(), - 'points': [(x_bottom, y_bottom), (x_top, y_top)], - 'model_type': model_type, - 'confidence': confidence, - 'num_lines': len(lines) - } - - def _validate_lanes(self, left_lane: Optional[Dict], right_lane: Optional[Dict], - image_shape: Tuple[int, ...]) -> Tuple[Optional[Dict], Optional[Dict]]: - """验证车道线合理性""" - if left_lane is None or right_lane is None: - return left_lane, right_lane - - height, width = image_shape[:2] - - # 检查车道宽度 - left_func = left_lane['func'] - right_func = right_lane['func'] - - y_points = np.linspace(height * 0.4, height, 5) - widths = [] - - for y in y_points: - left_x = left_func(y) - right_x = right_func(y) - if right_x > left_x: - widths.append(right_x - left_x) - - if widths: - avg_width = np.mean(widths) - std_width = np.std(widths) - - # 宽度合理性检查 - min_reasonable_width = width * 0.15 - max_reasonable_width = width * 0.8 - - if avg_width < min_reasonable_width or avg_width > max_reasonable_width or std_width > width * 0.2: - left_lane['confidence'] *= 0.7 - right_lane['confidence'] *= 0.7 - - # 检查车道线交叉 - if left_lane['points'][0][0] > right_lane['points'][0][0]: - left_lane['confidence'] *= 0.6 - right_lane['confidence'] *= 0.6 - - return left_lane, right_lane - - def _calculate_center_line(self, left_lane: Optional[Dict], right_lane: Optional[Dict], - image_shape: Tuple[int, ...]) -> Optional[Dict]: - """计算中心线""" - if left_lane is None or right_lane is None: - return None - - try: - left_func = left_lane['func'] - right_func = right_lane['func'] - - height, width = image_shape[:2] - - def center_func(y): - left_x = left_func(y) - right_x = right_func(y) - return (left_x + right_x) / 2 - - # 生成中心线点 - y_bottom = height - y_top = int(height * 0.4) - - x_bottom = int(center_func(y_bottom)) - x_top = int(center_func(y_top)) - - x_bottom = max(0, min(width, x_bottom)) - x_top = max(0, min(width, x_top)) - - confidence = (left_lane.get('confidence', 0) + right_lane.get('confidence', 0)) / 2 - - return { - 'func': center_func, - 'points': [(x_bottom, y_bottom), (x_top, y_top)], - 'confidence': confidence - } - - except Exception: - return None - - def _predict_future_path(self, left_lane: Optional[Dict], right_lane: Optional[Dict], - image_shape: Tuple[int, ...]) -> Optional[Dict]: - """预测未来路径""" - if left_lane is None or right_lane is None: - return None - - try: - height, width = image_shape[:2] - - # 计算中心线 - center_line = self._calculate_center_line(left_lane, right_lane, image_shape) - if center_line is None: - return None - - center_func = center_line['func'] - - # 生成预测点 - current_y = height - target_y = int(height * (1 - self.config.prediction_distance)) - - if target_y <= current_y * 0.6: - return None - - y_values = np.linspace(current_y, target_y, self.config.prediction_steps) - path_points = [] - - for y in y_values: - try: - x = center_func(y) - x = max(0, min(width, x)) - path_points.append((int(x), int(y))) - except: - continue - - if len(path_points) < self.config.min_prediction_points: - return None - - return { - 'center_path': path_points, - 'prediction_length': len(path_points) - } - - except Exception: - return None - - def _calculate_detection_quality(self, left_lane: Optional[Dict], right_lane: Optional[Dict]) -> float: - """计算检测质量""" - quality = 0.0 - - if left_lane is not None: - quality += left_lane['confidence'] * 0.5 - - if right_lane is not None: - quality += right_lane['confidence'] * 0.5 - - if left_lane is not None and right_lane is not None: - quality += 0.1 - if left_lane['model_type'] == right_lane['model_type']: - quality += 0.1 - - return min(quality, 1.0) - - def _apply_temporal_smoothing(self, current_result: Dict[str, Any]) -> Dict[str, Any]: - """应用时间平滑""" - if len(self.lane_history) < 2: - self.lane_history.append(current_result) - return current_result - - smoothing_factor = 0.6 - - # 平滑车道线参数 - if current_result['left_lane']: - for prev_result in list(self.lane_history)[-2:]: - if prev_result['left_lane']: - prev_coeffs = np.array(prev_result['left_lane']['coeffs']) - curr_coeffs = np.array(current_result['left_lane']['coeffs']) - - if len(prev_coeffs) == len(curr_coeffs): - smoothed_coeffs = ( - smoothing_factor * curr_coeffs + - (1 - smoothing_factor) * prev_coeffs - ) - current_result['left_lane']['coeffs'] = smoothed_coeffs.tolist() - current_result['left_lane']['func'] = np.poly1d(smoothed_coeffs) - - # 同样处理右车道线 - if current_result['right_lane']: - for prev_result in list(self.lane_history)[-2:]: - if prev_result['right_lane']: - prev_coeffs = np.array(prev_result['right_lane']['coeffs']) - curr_coeffs = np.array(current_result['right_lane']['coeffs']) - - if len(prev_coeffs) == len(curr_coeffs): - smoothed_coeffs = ( - smoothing_factor * curr_coeffs + - (1 - smoothing_factor) * prev_coeffs - ) - current_result['right_lane']['coeffs'] = smoothed_coeffs.tolist() - current_result['right_lane']['func'] = np.poly1d(smoothed_coeffs) - - self.lane_history.append(current_result) - return current_result - - def _create_empty_result(self) -> Dict[str, Any]: - """创建空结果""" - return { - 'left_lines': [], - 'right_lines': [], - 'left_lane': None, - 'right_lane': None, - 'center_line': None, - 'future_path': None, - 'detection_quality': 0.0 - } \ No newline at end of file diff --git a/src/lane_identification/software package/main.py b/src/lane_identification/software package/main.py deleted file mode 100644 index cdf44ee198..0000000000 --- a/src/lane_identification/software package/main.py +++ /dev/null @@ -1,530 +0,0 @@ -""" -主应用程序模块 - 负责界面和流程控制 -""" - -import tkinter as tk -from tkinter import filedialog, messagebox, ttk -import threading -import time -from typing import Dict, Any -from collections import deque -from PIL import Image, ImageTk -import cv2 -import numpy as np -import os - -# 导入各个模块 -from config import AppConfig -from image_processor import SmartImageProcessor, RoadDetector -from lane_detector import LaneDetector -from direction_analyzer import DirectionAnalyzer -from visualizer import Visualizer - -class LaneDetectionApp: - """道路方向识别系统主应用程序""" - - def __init__(self, root): - self.root = root - self._setup_window() - - # 初始化配置 - self.config = AppConfig() - - # 初始化各个模块 - self.image_processor = SmartImageProcessor(self.config) - self.road_detector = RoadDetector(self.config) - self.lane_detector = LaneDetector(self.config) - self.direction_analyzer = DirectionAnalyzer(self.config) - self.visualizer = Visualizer(self.config) - - # 状态变量 - self.current_image = None - self.current_image_path = None - self.is_processing = False - self.processing_history = deque(maxlen=10) - - # 性能统计 - self.processing_times = [] - - # 创建界面 - self._create_ui() - - print("道路方向识别系统已启动") - - def _setup_window(self): - """设置窗口""" - self.root.title("道路方向识别系统") - self.root.geometry("1400x800") - self.root.minsize(1200, 700) - - # 设置窗口居中 - self.root.update_idletasks() - width = self.root.winfo_width() - height = self.root.winfo_height() - x = (self.root.winfo_screenwidth() // 2) - (width // 2) - y = (self.root.winfo_screenheight() // 2) - (height // 2) - self.root.geometry(f'{width}x{height}+{x}+{y}') - - def _create_ui(self): - """创建用户界面""" - # 主容器 - main_container = ttk.Frame(self.root) - main_container.pack(fill="both", expand=True, padx=10, pady=10) - - # 标题栏 - self._create_title_bar(main_container) - - # 内容区域 - content_frame = ttk.Frame(main_container) - content_frame.pack(fill="both", expand=True, pady=(10, 0)) - - # 左侧控制面板 - control_frame = self._create_control_panel(content_frame) - control_frame.pack(side="left", fill="y", padx=(0, 10)) - - # 右侧图像显示区域 - display_frame = self._create_display_panel(content_frame) - display_frame.pack(side="right", fill="both", expand=True) - - # 状态栏 - self._create_status_bar(main_container) - - def _create_title_bar(self, parent): - """创建标题栏""" - title_frame = ttk.Frame(parent) - title_frame.pack(fill="x", pady=(0, 10)) - - # 标题 - title_label = ttk.Label( - title_frame, - text="道路方向识别系统", - font=("微软雅黑", 16, "bold"), - foreground="#2c3e50" - ) - title_label.pack(side="left") - - # 版本信息 - version_label = ttk.Label( - title_frame, - text="v2.0", - font=("微软雅黑", 10), - foreground="#7f8c8d" - ) - version_label.pack(side="right") - - def _create_control_panel(self, parent): - """创建控制面板""" - control_frame = ttk.LabelFrame( - parent, - text="控制面板", - padding="15", - relief="groove" - ) - control_frame.pack_propagate(False) - control_frame.config(width=300) - - # 文件操作区域 - file_frame = ttk.LabelFrame(control_frame, text="文件操作", padding="10") - file_frame.pack(fill="x", pady=(0, 15)) - - # 选择图片按钮 - select_btn = ttk.Button( - file_frame, - text="选择图片", - command=self._select_image, - width=20 - ) - select_btn.pack(pady=(0, 10)) - - # 重新检测按钮 - self.redetect_btn = ttk.Button( - file_frame, - text="重新检测", - command=self._redetect, - width=20, - state="disabled" - ) - self.redetect_btn.pack(pady=(0, 10)) - - # 文件信息显示 - self.file_info_label = ttk.Label( - file_frame, - text="未选择图片", - wraplength=250, - foreground="#3498db" - ) - self.file_info_label.pack() - - # 参数调节区域 - param_frame = ttk.LabelFrame(control_frame, text="参数调节", padding="10") - param_frame.pack(fill="x", pady=(0, 15)) - - # 敏感度调节 - ttk.Label(param_frame, text="检测敏感度:").pack(anchor="w", pady=(0, 5)) - self.sensitivity_var = tk.DoubleVar(value=0.5) - sensitivity_scale = ttk.Scale( - param_frame, - from_=0.1, - to=1.0, - variable=self.sensitivity_var, - orient="horizontal", - command=self._on_parameter_change, - length=250 - ) - sensitivity_scale.pack(fill="x", pady=(0, 10)) - - # 结果显示区域 - result_frame = ttk.LabelFrame(control_frame, text="检测结果", padding="10") - result_frame.pack(fill="x") - - # 方向显示 - self.direction_label = ttk.Label( - result_frame, - text="等待检测...", - font=("微软雅黑", 14, "bold"), - foreground="#2c3e50" - ) - self.direction_label.pack(anchor="w", pady=(0, 5)) - - # 置信度显示 - self.confidence_label = ttk.Label( - result_frame, - text="", - font=("微软雅黑", 11) - ) - self.confidence_label.pack(anchor="w", pady=(0, 5)) - - # 检测质量显示 - self.quality_label = ttk.Label( - result_frame, - text="", - font=("微软雅黑", 10), - foreground="#7f8c8d" - ) - self.quality_label.pack(anchor="w", pady=(0, 5)) - - # 处理时间显示 - self.time_label = ttk.Label( - result_frame, - text="", - font=("微软雅黑", 9), - foreground="#95a5a6" - ) - self.time_label.pack(anchor="w") - - return control_frame - - def _create_display_panel(self, parent): - """创建显示面板""" - display_frame = ttk.Frame(parent) - - # 图像显示区域 - images_frame = ttk.Frame(display_frame) - images_frame.pack(fill="both", expand=True) - - # 原图显示 - original_frame = ttk.LabelFrame( - images_frame, - text="原始图像", - padding="5", - relief="groove" - ) - original_frame.pack(side="left", fill="both", expand=True, padx=(0, 5)) - - self.original_canvas = tk.Canvas( - original_frame, - bg="#ecf0f1", - highlightthickness=1, - highlightbackground="#bdc3c7" - ) - self.original_canvas.pack(fill="both", expand=True) - self.original_canvas.create_text( - 300, 200, - text="请选择道路图片", - font=("微软雅黑", 12), - fill="#7f8c8d" - ) - - # 结果图显示 - result_frame = ttk.LabelFrame( - images_frame, - text="检测结果", - padding="5", - relief="groove" - ) - result_frame.pack(side="right", fill="both", expand=True, padx=(5, 0)) - - self.result_canvas = tk.Canvas( - result_frame, - bg="#ecf0f1", - highlightthickness=1, - highlightbackground="#bdc3c7" - ) - self.result_canvas.pack(fill="both", expand=True) - self.result_canvas.create_text( - 300, 200, - text="检测结果将显示在这里", - font=("微软雅黑", 12), - fill="#7f8c8d" - ) - - return display_frame - - def _create_status_bar(self, parent): - """创建状态栏""" - status_frame = ttk.Frame(parent, relief="sunken", borderwidth=1) - status_frame.pack(fill="x", pady=(10, 0)) - - # 进度条 - self.progress_bar = ttk.Progressbar( - status_frame, - mode='indeterminate', - length=200 - ) - self.progress_bar.pack(side="left", fill="x", expand=True, padx=(5, 10), pady=5) - - # 状态文本 - self.status_var = tk.StringVar(value="就绪") - status_label = ttk.Label( - status_frame, - textvariable=self.status_var, - font=("微软雅黑", 9) - ) - status_label.pack(side="right", padx=(0, 10), pady=5) - - def _select_image(self): - """选择图片""" - if self.is_processing: - messagebox.showwarning("提示", "正在处理中,请稍候...") - return - - file_types = [ - ("图像文件", "*.jpg *.jpeg *.png *.bmp *.tiff"), - ("所有文件", "*.*") - ] - - file_path = filedialog.askopenfilename( - title="选择道路图片", - filetypes=file_types - ) - - if file_path: - self.current_image_path = file_path - self._load_image(file_path) - - def _load_image(self, file_path: str): - """加载图像""" - try: - # 更新界面状态 - self.status_var.set("正在加载图片...") - self.file_info_label.config(text=os.path.basename(file_path)) - self.redetect_btn.config(state="normal") - - # 在后台线程中处理 - thread = threading.Thread(target=self._process_image, args=(file_path,)) - thread.daemon = True - thread.start() - - except Exception as e: - messagebox.showerror("错误", f"加载图片失败: {str(e)}") - self.status_var.set("加载失败") - - def _process_image(self, file_path: str): - """处理图像""" - start_time = time.time() - - try: - # 标记为处理中 - self.is_processing = True - self.root.after(0, self._update_processing_state, True) - - # 1. 图像预处理 - result = self.image_processor.load_and_preprocess(file_path) - if result is None: - raise ValueError("无法处理图像") - - self.current_image, roi_info = result - - # 2. 道路检测 - road_info = self.road_detector.detect_road(self.current_image, roi_info['mask']) - - # 3. 车道线检测 - lane_info = self.lane_detector.detect(self.current_image, roi_info['mask']) - - # 4. 方向分析 - direction_info = self.direction_analyzer.analyze(road_info, lane_info) - - # 5. 创建可视化 - visualization = self.visualizer.create_visualization( - self.current_image, road_info, lane_info, direction_info - ) - - processing_time = time.time() - start_time - - # 在主线程中更新UI - self.root.after(0, self._update_results, - direction_info, lane_info, visualization, processing_time) - - # 更新统计信息 - self.processing_times.append(processing_time) - if len(self.processing_times) > 10: - self.processing_times.pop(0) - - # 记录处理历史 - self.processing_history.append({ - 'file': file_path, - 'time': processing_time, - 'direction': direction_info['direction'], - 'confidence': direction_info['confidence'] - }) - - except Exception as e: - print(f"处理失败: {e}") - self.root.after(0, self._show_error, str(e)) - - finally: - self.is_processing = False - self.root.after(0, self._update_processing_state, False) - - def _update_processing_state(self, is_processing: bool): - """更新处理状态""" - if is_processing: - self.progress_bar.start() - self.status_var.set("正在分析...") - self.redetect_btn.config(state="disabled") - else: - self.progress_bar.stop() - self.status_var.set("分析完成") - self.redetect_btn.config(state="normal") - - def _update_results(self, direction_info: Dict[str, Any], lane_info: Dict[str, Any], - visualization: np.ndarray, processing_time: float): - """更新结果""" - try: - # 显示图像 - self._display_image(self.current_image, self.original_canvas, "原始图像") - self._display_image(visualization, self.result_canvas, "检测结果") - - # 获取信息 - direction = direction_info['direction'] - confidence = direction_info['confidence'] - quality = lane_info.get('detection_quality', 0.0) - - # 更新方向信息 - self.direction_label.config(text=f"方向: {direction}") - - # 设置置信度文本和颜色 - if confidence > 0.7: - color = "#27ae60" # 绿色 - confidence_text = f"置信度: {confidence:.1%} (高)" - elif confidence > 0.4: - color = "#f39c12" # 橙色 - confidence_text = f"置信度: {confidence:.1%} (中)" - else: - color = "#e74c3c" # 红色 - confidence_text = f"置信度: {confidence:.1%} (低)" - - self.confidence_label.config(text=confidence_text, foreground=color) - - # 设置检测质量 - self.quality_label.config(text=f"检测质量: {quality:.1%}") - - # 设置处理时间 - self.time_label.config(text=f"处理时间: {processing_time:.3f}秒") - - # 更新状态 - self.status_var.set(f"分析完成 - {direction}") - - print(f"处理完成: 方向={direction}, 置信度={confidence:.1%}, 耗时={processing_time:.3f}s") - - except Exception as e: - print(f"更新结果失败: {e}") - self.status_var.set("更新结果失败") - - def _display_image(self, image: np.ndarray, canvas: tk.Canvas, title: str): - """在Canvas上显示图像""" - try: - canvas.delete("all") - - if image is None: - canvas.create_text(300, 200, text=f"{title}加载失败", fill="red") - return - - # 转换颜色空间 - image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) - pil_image = Image.fromarray(image_rgb) - - # 获取Canvas尺寸 - canvas_width = canvas.winfo_width() - canvas_height = canvas.winfo_height() - - if canvas_width <= 1 or canvas_height <= 1: - canvas_width, canvas_height = 600, 400 - - # 计算缩放比例 - img_width, img_height = pil_image.size - scale = min(canvas_width / img_width, canvas_height / img_height) - - if scale < 1: - new_size = (int(img_width * scale), int(img_height * scale)) - pil_image = pil_image.resize(new_size, Image.Resampling.LANCZOS) - - # 转换为Tkinter格式 - photo = ImageTk.PhotoImage(pil_image) - - # 居中显示 - x = (canvas_width - photo.width()) // 2 - y = (canvas_height - photo.height()) // 2 - - canvas.create_image(x, y, anchor="nw", image=photo) - canvas.image = photo # 保持引用 - - except Exception as e: - print(f"显示图像失败: {e}") - canvas.create_text(150, 150, text="图像显示失败", fill="red") - - def _redetect(self): - """重新检测""" - if self.current_image_path and not self.is_processing: - self._process_image(self.current_image_path) - - def _on_parameter_change(self, value): - """参数变化回调""" - # 更新配置 - sensitivity = self.sensitivity_var.get() - - # 根据敏感度调整参数 - self.config.canny_threshold1 = int(30 + sensitivity * 40) - self.config.canny_threshold2 = int(80 + sensitivity * 100) - self.config.hough_threshold = int(20 + (1 - sensitivity) * 30) - - print(f"参数更新: 敏感度={sensitivity:.2f}") - - # 如果已有图像,自动重新检测 - if self.current_image_path and not self.is_processing: - self._redetect() - - def _show_error(self, error_msg: str): - """显示错误""" - messagebox.showerror("错误", f"处理失败: {error_msg}") - self.status_var.set("处理失败") - - -def main(): - """主函数""" - try: - # 创建主窗口 - root = tk.Tk() - - # 创建应用程序实例 - app = LaneDetectionApp(root) - - # 运行主循环 - root.mainloop() - - except Exception as e: - print(f"应用程序启动失败: {e}") - messagebox.showerror("致命错误", f"应用程序启动失败: {str(e)}") - -if __name__ == "__main__": - main() \ No newline at end of file diff --git a/src/lane_identification/software package/visualizer.py b/src/lane_identification/software package/visualizer.py deleted file mode 100644 index 050070f9c8..0000000000 --- a/src/lane_identification/software package/visualizer.py +++ /dev/null @@ -1,314 +0,0 @@ -""" -可视化模块 - 负责结果可视化显示 -""" - -import cv2 -import numpy as np -from typing import Dict, Any, Tuple -from config import AppConfig - -class Visualizer: - """可视化引擎""" - - def __init__(self, config: AppConfig): - self.config = config - self._setup_colors() - - def _setup_colors(self): - """设置颜色方案""" - self.colors = { - # 道路相关 - 'road_area': (0, 180, 0, 100), - 'road_boundary': (0, 255, 255, 200), - - # 车道线 - 'left_lane': (255, 100, 100, 200), - 'right_lane': (100, 100, 255, 200), - 'center_line': (255, 255, 0, 180), - - # 路径预测 - 'future_path': (255, 0, 255, 180), - 'prediction_points': (255, 150, 255, 220), - - # 置信度颜色 - 'confidence_high': (0, 255, 0), - 'confidence_medium': (255, 165, 0), - 'confidence_low': (255, 0, 0), - 'confidence_very_low': (128, 128, 128), - - # 文本颜色 - 'text_primary': (255, 255, 255), - 'text_secondary': (200, 200, 200), - } - - def create_visualization(self, image: np.ndarray, - road_info: Dict[str, Any], - lane_info: Dict[str, Any], - direction_info: Dict[str, Any]) -> np.ndarray: - """创建可视化结果""" - try: - # 创建副本 - visualization = image.copy() - - # 1. 绘制道路区域 - if road_info.get('contour') is not None: - visualization = self._draw_road_area(visualization, road_info) - - # 2. 绘制车道线 - visualization = self._draw_lanes(visualization, lane_info) - - # 3. 绘制路径预测 - if lane_info.get('future_path'): - visualization = self._draw_future_path(visualization, lane_info['future_path']) - - # 4. 绘制信息面板 - visualization = self._draw_info_panel(visualization, direction_info, lane_info) - - # 5. 绘制方向指示器 - visualization = self._draw_direction_indicator(visualization, direction_info) - - # 6. 应用全局效果 - visualization = self._apply_global_effects(visualization) - - return visualization - - except Exception as e: - print(f"可视化创建失败: {e}") - return image - - def _draw_road_area(self, image: np.ndarray, road_info: Dict[str, Any]) -> np.ndarray: - """绘制道路区域""" - contour = road_info['contour'] - if contour is None or len(contour) == 0: - return image - - # 创建道路图层 - road_layer = image.copy() - - # 填充道路区域 - cv2.drawContours(road_layer, [contour], -1, self.colors['road_area'][:3], -1) - - # 绘制道路边界 - cv2.drawContours(road_layer, [contour], -1, self.colors['road_boundary'][:3], 2) - - # 混合图层 - alpha = self.colors['road_area'][3] / 255.0 - cv2.addWeighted(road_layer, alpha, image, 1 - alpha, 0, image) - - return image - - def _draw_lanes(self, image: np.ndarray, lane_info: Dict[str, Any]) -> np.ndarray: - """绘制车道线""" - lane_layer = image.copy() - - # 绘制原始检测线段 - for side, color_key in [('left_lines', 'left_lane'), ('right_lines', 'right_lane')]: - lines = lane_info.get(side, []) - color = self.colors[color_key] - - for line in lines: - points = line.get('points', []) - if len(points) == 2: - cv2.line(lane_layer, points[0], points[1], color[:3], 1, cv2.LINE_AA) - - # 绘制拟合的车道线 - for side, color_key in [('left_lane', 'left_lane'), ('right_lane', 'right_lane')]: - lane = lane_info.get(side) - if lane and 'points' in lane and len(lane['points']) == 2: - points = lane['points'] - color = self.colors[color_key] - - # 根据置信度调整线条粗细 - confidence = lane.get('confidence', 0.5) - thickness = 2 + int(confidence * 4) - - cv2.line(lane_layer, points[0], points[1], color[:3], thickness, cv2.LINE_AA) - - # 绘制中心线 - center_line = lane_info.get('center_line') - if center_line and 'points' in center_line and len(center_line['points']) == 2: - points = center_line['points'] - color = self.colors['center_line'] - cv2.line(lane_layer, points[0], points[1], color[:3], 2, cv2.LINE_AA) - - # 混合车道线图层 - cv2.addWeighted(lane_layer, 0.7, image, 0.3, 0, image) - - return image - - def _draw_future_path(self, image: np.ndarray, future_path: Dict[str, Any]) -> np.ndarray: - """绘制未来路径""" - path_points = future_path.get('center_path', []) - if len(path_points) < 2: - return image - - path_layer = image.copy() - color = self.colors['future_path'] - - # 绘制渐变路径线 - for i in range(len(path_points) - 1): - # 计算透明度渐变 - alpha_factor = 0.5 + 0.5 * (i / (len(path_points) - 1)) - line_color = tuple(int(c * alpha_factor) for c in color[:3]) - - # 线条粗细渐变 - thickness = 5 - int(i / len(path_points) * 3) - - cv2.line(path_layer, path_points[i], path_points[i + 1], - line_color, thickness, cv2.LINE_AA) - - # 混合路径图层 - cv2.addWeighted(path_layer, 0.6, image, 0.4, 0, image) - - return image - - def _draw_info_panel(self, image: np.ndarray, direction_info: Dict[str, Any], - lane_info: Dict[str, Any]) -> np.ndarray: - """绘制信息面板""" - height, width = image.shape[:2] - - # 创建半透明背景 - panel_height = 120 - overlay = image.copy() - cv2.rectangle(overlay, (0, 0), (width, panel_height), (0, 0, 0, 180), -1) - cv2.addWeighted(overlay, 0.7, image, 0.3, 0, image) - - # 获取信息 - direction = direction_info.get('direction', '未知') - confidence = direction_info.get('confidence', 0.0) - quality = lane_info.get('detection_quality', 0.0) - - # 设置颜色 - confidence_color = self._get_confidence_color(confidence) - - # 绘制方向信息 - font = cv2.FONT_HERSHEY_SIMPLEX - - # 1. 方向 - direction_text = f"方向: {direction}" - cv2.putText(image, direction_text, (20, 35), - font, 1.2, confidence_color, 2) - - # 2. 置信度 - confidence_text = f"置信度: {confidence:.1%}" - cv2.putText(image, confidence_text, (20, 70), - font, 0.9, confidence_color, 2) - - # 3. 检测质量 - quality_text = f"检测质量: {quality:.1%}" - cv2.putText(image, quality_text, (20, 100), - font, 0.7, self.colors['text_secondary'], 1) - - # 4. 概率分布(右侧) - if 'probabilities' in direction_info: - probabilities = direction_info['probabilities'] - start_x = width - 200 - start_y = 30 - - for i, (dir_name, prob) in enumerate(probabilities.items()): - y = start_y + i * 25 - prob_text = f"{dir_name}: {prob:.1%}" - - # 高亮当前方向 - color = self.colors['text_primary'] if dir_name == direction else self.colors['text_secondary'] - - cv2.putText(image, prob_text, (start_x, y), - font, 0.7, color, 1) - - return image - - def _draw_direction_indicator(self, image: np.ndarray, - direction_info: Dict[str, Any]) -> np.ndarray: - """绘制方向指示器""" - height, width = image.shape[:2] - direction = direction_info.get('direction', '未知') - confidence = direction_info.get('confidence', 0.0) - - # 指示器位置(底部中央) - center_x = width // 2 - indicator_y = height - 150 - - # 创建指示器图层 - indicator_layer = np.zeros_like(image) - - # 根据方向绘制指示器 - if direction == "左转": - # 左转箭头 - points = np.array([ - [center_x, indicator_y], - [center_x - 80, indicator_y], - [center_x - 60, indicator_y - 40], - [center_x - 100, indicator_y - 40], - [center_x - 120, indicator_y], - [center_x - 200, indicator_y], - [center_x - 100, indicator_y + 80], - [center_x, indicator_y + 80] - ], dtype=np.int32) - base_color = (0, 165, 255) # 橙色 - - elif direction == "右转": - # 右转箭头 - points = np.array([ - [center_x, indicator_y], - [center_x + 80, indicator_y], - [center_x + 60, indicator_y - 40], - [center_x + 100, indicator_y - 40], - [center_x + 120, indicator_y], - [center_x + 200, indicator_y], - [center_x + 100, indicator_y + 80], - [center_x, indicator_y + 80] - ], dtype=np.int32) - base_color = (0, 165, 255) # 橙色 - - else: # 直行或未知 - # 直行箭头 - points = np.array([ - [center_x - 60, indicator_y + 40], - [center_x, indicator_y - 40], - [center_x + 60, indicator_y + 40], - [center_x + 40, indicator_y + 40], - [center_x + 40, indicator_y + 120], - [center_x - 40, indicator_y + 120], - [center_x - 40, indicator_y + 40] - ], dtype=np.int32) - base_color = (0, 255, 0) # 绿色 - - # 根据置信度调整颜色亮度 - brightness_factor = 0.5 + confidence * 0.5 - color = tuple(int(c * brightness_factor) for c in base_color) - - # 绘制指示器 - cv2.fillPoly(indicator_layer, [points], color) - - # 根据置信度调整透明度 - alpha = 0.3 + confidence * 0.5 - cv2.addWeighted(indicator_layer, alpha, image, 1 - alpha, 0, image) - - # 绘制边框 - cv2.polylines(image, [points], True, (255, 255, 255), 2, cv2.LINE_AA) - - return image - - def _get_confidence_color(self, confidence: float) -> Tuple[int, int, int]: - """根据置信度获取颜色""" - if confidence >= 0.8: - return self.colors['confidence_high'] - elif confidence >= 0.6: - return self.colors['confidence_medium'] - elif confidence >= 0.4: - return self.colors['confidence_low'] - else: - return self.colors['confidence_very_low'] - - def _apply_global_effects(self, image: np.ndarray) -> np.ndarray: - """应用全局效果""" - # 轻微锐化 - kernel = np.array([[-1, -1, -1], - [-1, 9, -1], - [-1, -1, -1]]) - sharpened = cv2.filter2D(image, -1, kernel) - - # 混合原始和锐化图像 - cv2.addWeighted(sharpened, 0.3, image, 0.7, 0, image) - - return image \ No newline at end of file