# 高光谱图像分类与分析工具包 - 完整技术文档 [![Python Version](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/) [![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE) [![Documentation](https://img.shields.io/badge/docs-complete-brightgreen.svg)]() ## 目录 1. [项目概述](#1-项目概述) 2. [核心功能特性](#2-核心功能特性) 3. [系统架构图](#3-系统架构图) 4. [模块说明](#4-模块说明) 5. [数据流程](#5-数据流程) 6. [安装部署指南](#6-安装部署指南) 7. [API接口文档](#7-api接口文档) 8. [使用示例](#8-使用示例) 9. [配置说明](#9-配置说明) 10. [维护指南](#10-维护指南) --- ## 1. 项目概述 ### 1.1 项目简介 高光谱图像分类与分析工具包是一个全面的机器学习和图像处理框架,专门为高光谱遥感数据分析设计。该工具包提供了从数据预处理到模型训练的完整解决方案,支持多种机器学习算法和图像处理技术。 ### 1.2 主要目标 - **统一接口**: 为高光谱数据分析提供一致的API接口 - **模块化设计**: 支持灵活的功能组合和扩展 - **高性能计算**: 优化算法实现,支持大规模数据处理 - **易用性**: 简化的配置系统和丰富的文档支持 ### 1.3 技术栈 - **核心语言**: Python 3.8+ - **机器学习**: scikit-learn, XGBoost, LightGBM, CatBoost - **图像处理**: OpenCV, scikit-image, Pillow - **科学计算**: NumPy, SciPy, Pandas - **颜色科学**: colour-science - **数据处理**: GDAL, spectral, joblib ### 1.4 项目特色 1. **配置驱动架构**: 使用数据类和配置验证确保参数正确性 2. **智能算法选择**: 基于数据特征自动推荐最适合的算法 3. **批量处理能力**: 支持多参数、多方法的并行处理 4. **ENVI格式支持**: 完整的ENVI高光谱数据格式读写支持 5. **GUI就绪**: 为图形界面集成优化的API设计 --- ## 2. 核心功能特性 ### 2.1 数据处理能力 | 功能模块 | 支持格式 | 关键特性 | |---------|---------|---------| | **数据加载** | ENVI(.hdr/.dat), CSV, GeoTIFF | 自动格式检测,多波段处理 | | **预处理** | 标准化、归一化、异常值处理 | 可配置的预处理流水线 | | **特征工程** | PCA, ICA, LDA, 自定义特征 | 降维和特征选择算法 | ### 2.2 机器学习算法 #### 分类算法 - **传统算法**: SVM, 随机森林, KNN, 逻辑回归, LDA/QDA - **集成方法**: AdaBoost, XGBoost, LightGBM, CatBoost - **聚类算法**: K-Means, 层次聚类, DBSCAN, 高斯混合模型 #### 回归算法 - **线性模型**: 线性回归, 岭回归, LASSO, 弹性网络 - **非线性模型**: SVR, 高斯过程, KNN回归 - **集成回归**: 随机森林回归, 梯度提升回归 ### 2.3 图像处理算法 #### 空间滤波 - **平滑滤波**: 均值滤波, 高斯滤波, 中值滤波, 双边滤波 - **形态学操作**: 腐蚀, 膨胀, 开运算, 闭运算, 形态学梯度 #### 特征提取 - **边缘检测**: Sobel, Scharr, Laplacian, LoG, Canny - **分割算法**: 阈值分割, 区域生长, 分水岭算法 - **纹理分析**: GLCM, Gabor滤波器, 小波变换 - **形状分析**: 连通域分析, 形状特征提取, Hu不变矩, 轮廓分析 ### 2.4 颜色处理算法 #### 光谱颜色转换 - **光谱转XYZ**: 高光谱数据转CIE XYZ三刺激值 - **XYZ转RGB**: XYZ到RGB颜色空间转换 - **标准光源**: D65、D50、A、F系列等标准光源 - **观察者**: CIE 1931 2° 和 CIE 1964 10° 标准观察者 #### 色差计算 - **Delta E方法**: CIE76、CIE94、CIEDE2000色差公式 - **颜色比较**: 图像像素与标准色库的色差计算 - **配对比较**: 任意两组颜色的色差分析 - **可视化输出**: 热图和直方图展示色差分布 #### RGB颜色空间 - **标准空间**: sRGB、Adobe RGB、DCI-P3、BT.709等 - **专业空间**: ProPhoto RGB、ACES2065-1、ACEScg - **伽马校正**: sRGB、BT.709、gamma 1.8、gamma 2.2等 - **HDR支持**: BT.1886、PQ (ST 2084)、HLG曲线 ### 2.4 光谱分析 #### 光谱指数计算 - **植被指数**: NDVI, EVI, ARVI, SAVI, LAI - **水分指数**: NDWI, MNDWI, NDMI - **土壤指数**: NDSI, BI, SI - **自定义公式**: 用户定义的光谱指数计算 #### 降维分析 - **线性方法**: PCA, ICA, FA - **非线性方法**: MDS, Isomap, LLE, t-SNE - **监督方法**: LDA (线性判别分析) ### 2.5 高级特性 - **自动调参**: 网格搜索, 随机搜索, 贝叶斯优化 - **模型评估**: 交叉验证, ROC曲线, 混淆矩阵, 分类报告 - **模型持久化**: Pickle格式的模型保存和加载 - **批量处理**: 多参数组合的并行计算支持 --- ## 3. 系统架构图 ```mermaid graph TB A[用户接口层] --> B[配置管理层] B --> C[业务逻辑层] C --> D[算法执行层] D --> E[数据处理层] subgraph "用户接口层" F[命令行接口] G[Python API] H[GUI集成接口] end subgraph "配置管理层" I[数据类配置] J[参数验证] K[配置序列化] end subgraph "业务逻辑层" L[数据加载器] M[预处理器] N[特征选择器] O[模型训练器] P[结果评估器] end subgraph "算法执行层" Q[分类算法] R[回归算法] S[聚类算法] T[图像处理算法] U[光谱分析算法] end subgraph "数据处理层" V[ENVI格式处理] W[CSV处理] X[图像IO] Y[结果保存] end Z[外部依赖] --> E Z --> D ``` ### 架构说明 1. **用户接口层**: 提供多种交互方式,包括命令行、Python API和GUI集成 2. **配置管理层**: 集中化参数管理和验证,确保配置的正确性和一致性 3. **业务逻辑层**: 核心业务流程控制,协调各个组件的工作 4. **算法执行层**: 具体的机器学习和图像处理算法实现 5. **数据处理层**: 数据格式转换、读写操作和结果持久化 --- ## 4. 模块说明 ### 4.1 核心模块列表 | 模块名称 | 文件路径 | 主要功能 | 依赖关系 | |---------|---------|---------|---------| | **数据预处理** | `preprocessing_method/Preprocessing.py` | 数据清洗、标准化、格式转换 | numpy, pandas, scipy | | **特征选择** | `Feature_Selection_method/feture_select.py` | 特征重要性评估、特征子集选择 | scikit-learn, numpy | | **降维分析** | `Dimensionality_Reduction_method/dimensionality_reduction.py` | 高维数据降维、流形学习 | scikit-learn, numpy, scipy | | **分类算法** | `classfication_method/classfication.py` | 监督学习分类、多模型对比 | scikit-learn, xgboost, lightgbm | | **聚类算法** | `cluster_method/cluster.py` | 无监督聚类、聚类评估 | scikit-learn, numpy | | **监督聚类** | `supervize_cluster_method/supervize_cluster.py` | 半监督聚类算法 | scikit-learn, numpy | | **回归分析** | `rgression_method/regression.py` | 回归模型训练和评估 | scikit-learn, xgboost, lightgbm | | **图像滤波** | `fliter_method/Smooth_filter.py` | 空间域滤波算法 | opencv-python, numpy | | **形态学滤波** | `fliter_method/morphological_fliter.py` | 形态学图像处理 | opencv-python, numpy | | **阈值分割** | `segment_method/threshold_Segment.py` | 图像阈值分割算法 | opencv-python, numpy | | **边缘检测** | `edge_detect_method/edge_detect.py` | 多尺度边缘检测 | opencv-python, scipy | | **空间特征** | `spatial_features_method/` | 纹理和形状特征提取 | scikit-image, opencv-python, numpy | | **光谱指数** | `spectral_index_method/spectral_index.py` | 光谱指数计算和分析 | numpy, pandas | | **Delta E色差** | `color_method/DeltaE.py` | 颜色差异计算和分析 | colour-science, numpy, spectral | | **光谱转颜色** | `color_method/spectral2cie2.py` | 高光谱数据转CIE颜色空间 | colour-science, numpy, spectral | | **XYZ转RGB** | `color_method/XYZ2RGB.py` | XYZ到RGB颜色空间转换 | colour-science, numpy, spectral | ### 4.2 模块依赖关系图 ```mermaid graph TD A[preprocessing_method] --> B[Feature_Selection_method] A --> C[classfication_method] A --> D[cluster_method] A --> E[rgression_method] B --> C B --> D B --> E F[Dimensionality_Reduction_method] --> C F --> D F --> E G[fliter_method] --> H[segment_method] G --> I[edge_detect_method] H --> K[spatial_features_method] J[spectral_index_method] --> A L[color_method] --> A L --> M[classfication_method] L --> N[cluster_method] subgraph "颜色处理模块" O[DeltaE.py] --> L P[spectral2cie2.py] --> L Q[XYZ2RGB.py] --> L end ``` --- ## 5. 数据流程 ### 5.1 典型工作流程 ```mermaid sequenceDiagram participant U as 用户 participant C as 配置系统 participant L as 数据加载器 participant P as 预处理器 participant F as 特征选择器 participant M as 模型训练器 participant E as 评估器 participant S as 结果保存器 U->>C: 配置参数 C->>C: 参数验证 U->>L: 加载数据 L->>P: 数据预处理 P->>F: 特征选择 F->>M: 模型训练 M->>E: 模型评估 E->>S: 保存结果 S->>U: 返回结果 ``` ### 5.2 数据格式转换 1. **输入格式支持**: - ENVI格式 (.hdr + .dat): 高光谱数据标准格式 - CSV格式: 表格数据,包含标签和特征 - GeoTIFF: 地理空间栅格数据 - NumPy数组: 内存中的多维数组 2. **内部数据结构**: - `X`: 特征矩阵 (n_samples, n_features) - `y`: 标签向量 (n_samples,) - `X_reduced`: 降维后的特征矩阵 - `results`: 模型预测结果字典 3. **输出格式**: - ENVI格式: 处理后的高光谱数据 - CSV格式: 分类结果和统计信息 - Pickle格式: 训练好的模型 - JSON格式: 配置和评估结果 --- ## 6. 安装部署指南 ### 6.1 系统要求 #### 硬件要求 - **CPU**: Intel i5 或同等性能处理器 - **内存**: 8GB RAM (推荐16GB用于大型数据集) - **存储**: 10GB 可用磁盘空间 - **GPU**: NVIDIA GPU (可选,用于深度学习) #### 软件要求 - **操作系统**: Windows 10+, Ubuntu 18.04+, macOS 10.15+ - **Python版本**: 3.8 - 3.11 ### 6.2 安装步骤 #### 1. 克隆项目 ```bash git clone cd hyperspectral-toolkit ``` #### 2. 创建虚拟环境 ```bash # Windows python -m venv hyperspectral_env hyperspectral_env\Scripts\activate # Linux/Mac python -m venv hyperspectral_env source hyperspectral_env/bin/activate ``` #### 3. 安装核心依赖 ```bash pip install -r requirements.txt ``` #### 4. 安装可选依赖 ```bash # 深度学习支持 pip install tensorflow # 或 torch # GPU加速 pip install tensorflow-gpu # CUDA版本 # 开发工具 pip install jupyter pytest ``` ### 6.3 依赖包详细说明 | 包名 | 版本 | 用途 | 是否必需 | |-----|------|------|---------| | numpy | >=1.21.0 | 数值计算基础 | 是 | | pandas | >=1.3.0 | 数据处理 | 是 | | scikit-learn | >=1.0.0 | 机器学习算法 | 是 | | opencv-python | >=4.5.0 | 图像处理 | 是 | | spectral | >=0.22.0 | ENVI格式处理 | 是 | | colour-science | >=0.4.0 | 颜色科学计算 | 否 | | xgboost | >=1.5.0 | 梯度提升 | 否 | | lightgbm | >=3.3.0 | 快速梯度提升 | 否 | | matplotlib | >=3.5.0 | 可视化 | 否 | ### 6.4 验证安装 ```python # 运行测试 python -c "import numpy, pandas, sklearn; print('核心依赖安装成功')" # 测试图像处理 python -c "import cv2; print('OpenCV版本:', cv2.__version__)" # 测试高光谱处理 python -c "import spectral; print('Spectral库可用')" ``` --- ## 7. API接口文档 ### 7.1 配置类接口 #### DimensionalityReductionConfig ```python @dataclass class DimensionalityReductionConfig: """高光谱数据降维配置类""" # 输入配置 input_path: str = None label_col: str = None spectral_start: str = None spectral_end: str = None # 降维配置 method: str = 'PCA' n_components: int = 3 method_params: Dict[str, Any] = field(default_factory=dict) # 批量处理配置 batch_methods: List[str] = field(default_factory=lambda: ['PCA', 'ICA', 'FA']) batch_components: List[int] = field(default_factory=lambda: [3, 3, 3]) ``` **方法**: - `__post_init__()`: 参数验证和初始化 #### ThresholdSegmentationConfig ```python @dataclass class ThresholdSegmentationConfig: """阈值分割配置类""" input_path: str = None band_index: int = 0 method: str = 'otsu' threshold_value: float = None # 自适应阈值参数 adaptive_block_size: int = 11 adaptive_c: float = 2.0 # Canny参数 canny_min_threshold: int = 100 canny_max_threshold: int = 200 ``` #### ShapeFeatureConfig ```python @dataclass class ShapeFeatureConfig: """形状特征分析配置类""" # 输入数据设置 input_type: str = 'dat' # 'dat' 或 'shp' dat_file_path: str = None # dat文件路径 hdr_file_path: str = None # 对应的hdr文件路径 shp_file_path: str = None # shp文件路径 band_index: int = 0 # 要处理的波段索引 # 连通域处理参数 connectivity: int = 8 # 连通性:4或8 min_area: int = 10 # 最小区域面积阈值 use_watershed: bool = False # 是否使用分水岭算法分离相邻物体 # 分水岭算法参数 watershed_min_distance: int = 10 # 局部最大值的最小距离 # 输出设置 output_dir: str = "output" output_csv: bool = True # 是否保存为CSV文件 save_labeled_image: bool = False # 是否保存标记后的图像 ``` ### 7.2 核心类接口 #### HyperspectralDimReduction ```python class HyperspectralDimReduction: """高光谱数据降维处理系统""" def __init__(self, config: DimensionalityReductionConfig) def load_data(self) -> None def apply_dim_reduction(self) -> Tuple[np.ndarray, List[str]] def batch_process(self, methods, n_components_list, output_dir) -> Dict def save_results(self, reduced_data, band_names, output_path, method) def get_recommended_methods(...) -> Dict def print_method_info() ``` **关键方法说明**: | 方法 | 参数 | 返回值 | 说明 | |------|------|-------|------| | `load_data()` | 无 | None | 加载和预处理数据 | | `apply_dim_reduction()` | 无 | (data, band_names) | 执行降维 | | `batch_process()` | methods, components, output_dir | results_dict | 批量处理 | #### ThresholdSegmenter ```python class ThresholdSegmenter: """阈值分割处理系统""" def __init__(self, config: ThresholdSegmentationConfig) def load_data(self) -> None def apply_segmentation(self) -> Tuple[np.ndarray, float] def batch_process(self, methods, bands, output_dir) -> Dict def save_results(self, data, threshold, output_path, method) ``` #### Shape Feature Analysis Functions ```python def analyze_shape_features(config: ShapeFeatureConfig) -> Tuple[pd.DataFrame, np.ndarray]: """执行完整的形状特征分析流程""" def load_binary_image_from_dat(dat_path: str, hdr_path: str = None, band_index: int = 0) -> Tuple[np.ndarray, Dict]: """从ENVI dat文件加载二值化图像数据""" def load_regions_from_shp(shp_path: str, image_shape: Tuple = None) -> Tuple[np.ndarray, Dict]: """从shp文件加载区域信息并转换为二值图像""" def label_connected_components(binary_image: np.ndarray, config: ShapeFeatureConfig) -> Tuple[np.ndarray, int]: """标记连通域,可选择使用分水岭算法""" def apply_watershed_segmentation(binary_image: np.ndarray, config: ShapeFeatureConfig) -> Tuple[np.ndarray, int]: """使用分水岭算法分离相邻物体""" def calculate_shape_features(labeled_image: np.ndarray, config: ShapeFeatureConfig) -> Tuple[pd.DataFrame, Dict]: """计算所有形状特征指标""" def save_features_to_csv(features_df: pd.DataFrame, output_path: str, config: ShapeFeatureConfig, contour_coords_dict: Dict = None) -> str: """将形状特征保存为CSV文件""" def save_labeled_image(labeled_image: np.ndarray, output_path: str, config: ShapeFeatureConfig) -> None: """保存标记后的图像""" ``` **形状特征指标说明**: | 特征名称 | 数据类型 | 范围 | 描述 | |---------|---------|------|------| | area | int | > 0 | 区域像素总数 | | perimeter | float | > 0 | 区域边界长度 | | circularity | float | [0, 1] | 圆形程度 (1=完美圆形) | | rectangularity | float | [0, 1] | 矩形相似度 | | aspect_ratio | float | > 0 | 宽高比 | | compactness | float | > 0 | 紧凑度 (越小越紧凑) | | eccentricity | float | [0, 1] | 椭圆离心率 | | hu_moment_1-7 | float | - | Hu不变矩 | | convexity | float | [0, 1] | 凸性度量 | | solidity | float | [0, 1] | 实体度量 | | contour_coords | str | - | 轮廓坐标引用 | #### EdgeDetector ```python class EdgeDetector: """边缘检测处理系统""" def __init__(self, config: EdgeDetectionConfig) def load_data(self) -> None def apply_edge_detection(self) -> Tuple[np.ndarray, Dict] def batch_process(self, methods, bands, output_dir) -> Dict ``` ### 7.3 异常处理 | 异常类型 | 触发条件 | 处理建议 | |---------|---------|---------| | `ValueError` | 参数无效 | 检查配置参数 | | `FileNotFoundError` | 文件不存在 | 验证文件路径 | | `ImportError` | 依赖缺失 | 安装所需包 | | `MemoryError` | 内存不足 | 减小数据集或增加内存 | --- ## 8. 使用示例 ### 8.1 基础使用示例 #### 降维分析 ```python from Dimensionality_Reduction_method.dimensionality_reduction import * # 创建配置 config = DimensionalityReductionConfig( input_path="hyperspectral_data.hdr", method='pca', n_components=5, output_dir='results' ) # 执行降维 processor = HyperspectralDimReduction(config) processor.load_data() reduced_data, band_names = processor.apply_dim_reduction() processor.save_results(reduced_data, band_names, 'pca_result.dat', 'pca') ``` #### 图像分割 ```python from segment_method.threshold_Segment import * config = ThresholdSegmentationConfig( input_path="image.hdr", band_index=100, method='otsu' ) processor = ThresholdSegmenter(config) processor.load_data() segmented, threshold = processor.apply_segmentation() processor.save_results(segmented, threshold, 'segmented.dat', 'otsu') ``` #### 边缘检测 ```python from edge_detect_method.edge_detect import * config = EdgeDetectionConfig( input_path="image.hdr", band_index=50, method='canny', canny_min_threshold=50, canny_max_threshold=150 ) processor = EdgeDetector(config) processor.load_data() edges, info = processor.apply_edge_detection() processor.save_results(edges, info, 'edges.dat', 'canny') ``` #### 形状特征分析 ```python from spatial_features_method.shape_feature import * # 基本配置 config = ShapeFeatureConfig() config.input_type = 'dat' config.dat_file_path = "segmented_image.dat" config.hdr_file_path = "segmented_image.hdr" config.band_index = 0 config.connectivity = 8 config.min_area = 50 config.use_watershed = False # 执行分析 features_df, labeled_image = analyze_shape_features(config) # 查看结果 print(f"分析完成,发现 {len(features_df)} 个连通域") print("提取的特征包括:") print("- 几何特征: area, perimeter, centroid") print("- 形状特征: circularity, rectangularity, aspect_ratio") print("- 不变矩: hu_moment_1-7") print("- 其他: convexity, solidity, compactness") ``` ### 8.2 高级使用示例 #### 批量处理 ```python # 批量降维分析 methods = ['pca', 'ica', 'fa', 'mds'] components = [5, 5, 5, 3] results = processor.batch_process(methods, components, 'batch_results') # 批量分割 methods = ['otsu', 'isodata', 'adaptive'] bands = [50, 50, 50] results = processor.batch_process(methods, bands, 'segmentation_results') ``` #### 自定义参数配置 ```python # 高级边缘检测配置 config = EdgeDetectionConfig( input_path="data.hdr", method='canny', canny_min_threshold=30, canny_max_threshold=100, canny_aperture_size=5, use_blur=True, blur_kernel_size=5, blur_sigma=1.2 ) ``` ### 8.3 集成使用示例 ```python # 完整的工作流程 from preprocessing_method.Preprocessing import * from Dimensionality_Reduction_method.dimensionality_reduction import * from classfication_method.classfication import * # 1. 数据预处理 preprocessor = DataPreprocessor(data_path="raw_data.csv") cleaned_data = preprocessor.clean_data() # 2. 降维处理 dim_config = DimensionalityReductionConfig( input_path="processed_data.hdr", method='pca', n_components=10 ) dim_reducer = HyperspectralDimReduction(dim_config) dim_reducer.load_data() reduced_data, _ = dim_reducer.apply_dim_reduction() # 3. 分类训练 classifier = HyperspectralClassifier() results = classifier.train_and_evaluate(reduced_data, labels) ``` --- ## 9. 配置说明 ### 9.1 配置系统架构 所有模块都使用基于数据类的配置系统,提供: - 类型检查和验证 - 默认值设置 - 参数文档化 - 配置序列化 ### 9.2 通用配置参数 | 参数名 | 类型 | 默认值 | 说明 | |-------|------|-------|------| | `input_path` | str | None | 输入文件路径 | | `output_path` | str | None | 输出文件路径 | | `output_dir` | str | None | 输出目录 | | `verbose` | bool | True | 是否显示详细信息 | ### 9.3 算法特定配置 #### 降维配置 ```python @dataclass class DimensionalityReductionConfig: method: str = 'pca' # 'pca', 'ica', 'fa', 'lda', 'mds', 'isomap', 'lle', 't-sne' n_components: int = 3 use_standardization: bool = True method_params: Dict = field(default_factory=dict) ``` #### 分割配置 ```python @dataclass class ThresholdSegmentationConfig: method: str = 'otsu' # 'fixed', 'histogram_bimodal', 'adaptive', 'iterative', 'otsu', 'isodata' threshold_value: float = None adaptive_block_size: int = 11 adaptive_c: float = 2.0 ``` #### 边缘检测配置 ```python @dataclass class EdgeDetectionConfig: method: str = 'canny' # 'sobel', 'scharr', 'laplacian', 'log', 'canny' kernel_size: int = 3 canny_min_threshold: int = 100 canny_max_threshold: int = 200 use_blur: bool = False ``` ### 9.4 配置验证规则 1. **路径验证**: 检查文件和目录的存在性 2. **参数范围**: 验证数值参数在合理范围内 3. **类型检查**: 确保参数类型正确 4. **依赖验证**: 检查必需的依赖包是否安装 --- ## 10. 维护指南 ### 10.1 代码规范 #### 命名规范 - 类名: PascalCase (如 `HyperspectralClassifier`) - 函数名: snake_case (如 `load_data()`) - 变量名: snake_case (如 `input_path`) - 常量: UPPER_CASE (如 `DEFAULT_CONFIG`) #### 文档规范 - 使用Google风格docstring - 包含参数类型和说明 - 提供使用示例 ### 10.2 测试策略 #### 单元测试 ```python # tests/test_dimensionality_reduction.py import pytest from Dimensionality_Reduction_method.dimensionality_reduction import * def test_pca_reduction(): config = DimensionalityReductionConfig( input_path="test_data.hdr", method='pca', n_components=3 ) processor = HyperspectralDimReduction(config) # 测试断言 ``` #### 集成测试 - 测试完整的数据处理流程 - 验证不同模块间的兼容性 - 性能基准测试 ### 10.3 性能优化 #### 内存优化 - 使用内存映射文件处理大型数据集 - 实现数据流处理避免一次性加载全部数据 - 使用垃圾回收优化内存使用 #### 计算优化 - 并行处理支持多核CPU - GPU加速支持(可选) - 算法复杂度优化 - **形状特征分析优化**: 连通域分析可并行化,分水岭算法复杂度O(n log n) ### 10.4 版本管理 #### 语义化版本 - MAJOR.MINOR.PATCH (如 1.2.3) - MAJOR: 不兼容的API变更 - MINOR: 向后兼容的功能新增 - PATCH: 向后兼容的bug修复 #### 分支策略 - `main`: 稳定版本 - `develop`: 开发分支 - `feature/*`: 功能分支 - `hotfix/*`: 紧急修复分支 ### 10.5 文档维护 #### 自动文档生成 ```bash # 生成API文档 sphinx-build docs/source docs/build # 更新README python scripts/update_readme.py ``` #### 变更日志 - 维护CHANGELOG.md文件 - 记录所有功能变更和修复 - 包含迁移指南 --- ## 模块详细文档 ### 4.3 Anomaly_method/ - 异常检测模块 #### 模块功能说明 高光谱异常检测模块,提供多种经典和现代异常检测算法,专门用于高光谱数据中的异常像素识别和分析。支持无监督和半监督检测方法,具有完整的预处理、检测和结果保存流程。 #### 支持的异常检测算法 1. **协方差异常检测 (Covariance.py)** - **算法原理**: 基于Minimum Covariance Determinant (MCD)估计的稳健协方差矩阵 - **适用场景**: 高维数据中的异常点检测,对异常值具有鲁棒性 - **优势**: 处理包含异常值的数据集效果佳,支持降维预处理 2. **单类SVM异常检测 (One_Class_SVM.py)** - **算法原理**: 使用One-Class SVM学习正常样本的决策边界 - **适用场景**: 非线性分布的异常检测,支持多种核函数 - **优势**: 能够学习复杂形状的决策边界,参数可调优 3. **RX算法异常检测 (RX.py)** - **算法原理**: 基于Mahalanobis距离的Reed-Xiaoli算法 - **适用场景**: 高光谱数据的全局和局部异常检测 - **优势**: 支持多尺度背景建模,计算效率高 4. **自重构异常检测 (squared_loss_probability.py)** - **算法原理**: 基于最小二乘自重构的异常检测 - **适用场景**: 完全无监督的异常检测,无需训练数据 - **优势**: 支持线性重构和PCA重构,检测精度高 #### 核心功能特性 1. **统一数据接口** - 支持ENVI和CSV格式的高光谱数据 - 自动数据预处理和格式转换 - 完整的异常检测结果保存 2. **多算法支持** - 四种经典异常检测算法 - 可配置的参数和预处理选项 - 自动阈值选择和结果评估 3. **高效计算** - 支持大规模高光谱数据处理 - 优化的矩阵运算和内存管理 - 并行处理能力 4. **结果可视化** - ENVI格式结果保存 - 统计信息输出 - 异常检测指标计算 #### 技术实现细节 ##### 数据预处理 - NaN值和无穷大值清理 - 可选的数据标准化 - 自动特征选择和降维 ##### 异常检测流程 1. 数据加载和预处理 2. 背景模型构建(适用于监督方法) 3. 异常分数计算 4. 阈值分割和结果输出 ##### 结果保存 - 多波段ENVI格式输出 - 包含检测参数的元数据 - 统计信息和评估指标 ### 4.4 Anomaly_method/Covariance.py #### 模块功能说明 基于协方差估计的异常检测器,使用scikit-learn的EllipticEnvelope类实现Minimum Covariance Determinant (MCD)算法。提供稳健的协方差估计,能够有效处理包含异常值的数据集。 #### 类和方法列表 | 类名 | 方法名 | 功能描述 | |-----|-------|---------| | `CovarianceAnomalyConfig` | `__post_init__()` | 配置验证和初始化 | | `CovarianceAnomalyDetector` | `__init__(config)` | 初始化检测器 | | | `load_data()` | 加载高光谱数据 | | | `preprocess_data()` | 数据预处理 | | | `fit_predict()` | 训练模型并预测 | | | `save_results()` | 保存检测结果 | #### 关键函数说明 **`fit_predict()`** - **功能**: 训练异常检测模型并进行预测 - **参数**: data (n_samples, n_features) - **返回值**: predictions (+1正常, -1异常), scores (马氏距离) - **异常**: ValueError (模型未训练) **`save_results()`** - **功能**: 保存异常检测结果为ENVI格式 - **参数**: output_path (可选) - **输出格式**: 多波段ENVI文件 (预测结果、马氏距离、异常分数) #### 使用示例 ```python from Anomaly_method.Covariance import CovarianceAnomalyConfig, CovarianceAnomalyDetector config = CovarianceAnomalyConfig( input_path="hyperspectral.hdr", contamination=0.1, use_dimensionality_reduction=True, n_components=10 ) detector = CovarianceAnomalyDetector(config) detector.load_data() processed_data = detector.preprocess_data() predictions, scores = detector.fit_predict(processed_data) detector.save_results() ``` #### 依赖关系说明 - scikit-learn: EllipticEnvelope和预处理算法 - numpy: 数值计算 - spectral: ENVI格式处理 - pandas: 数据处理 ### 4.5 Anomaly_method/One_Class_SVM.py #### 模块功能说明 One-Class SVM异常检测器,使用单类SVM算法进行无监督异常检测。只使用正常数据进行训练,能够学习复杂的决策边界。 #### 类和方法列表 | 类名 | 方法名 | 功能描述 | |-----|-------|---------| | `OneClassSVMConfig` | `__post_init__()` | 配置验证 | | `OneClassSVMDetector` | `__init__(config)` | 初始化检测器 | | | `load_data()` | 加载高光谱数据 | | | `preprocess_data()` | 数据预处理和PCA降维 | | | `train_model()` | 训练One-Class SVM模型 | | | `detect_anomalies()` | 执行异常检测 | | | `save_results()` | 保存检测结果 | #### 关键函数说明 **`train_model()`** - **功能**: 训练One-Class SVM模型 - **参数**: data (训练数据) - **输出**: 训练完成的SVM模型和决策函数 - **支持核函数**: linear, rbf, poly **`detect_anomalies()`** - **功能**: 检测测试数据中的异常 - **返回值**: predictions (+1正常, -1异常), scores (决策函数值) #### 使用示例 ```python from Anomaly_method.One_Class_SVM import OneClassSVMConfig, OneClassSVMDetector config = OneClassSVMConfig( input_path="hyperspectral.hdr", kernel='rbf', nu=0.1, use_pca=True, n_components=20 ) detector = OneClassSVMDetector(config) detector.load_data() processed_data = detector.preprocess_data(detector.data) detector.train_model(processed_data) predictions, scores = detector.detect_anomalies(processed_data) detector.save_results() ``` #### 依赖关系说明 - scikit-learn: OneClassSVM和预处理 - numpy: 数值计算 - spectral: 高光谱数据处理 ### 4.6 Anomaly_method/RX.py #### 模块功能说明 Reed-Xiaoli (RX) 异常检测器,基于Mahalanobis距离的高光谱异常检测算法。支持全局、局部行和局部正方形背景建模。 #### 类和方法列表 | 类名 | 方法名 | 功能描述 | |-----|-------|---------| | `RXConfig` | `__post_init__()` | 配置验证 | | `RXAnomalyDetector` | `__init__(config)` | 初始化检测器 | | | `load_data()` | 加载高光谱数据 | | | `compute_background_statistics()` | 计算背景统计量 | | | `detect_anomalies()` | 执行异常检测 | | | `save_results()` | 保存检测结果 | #### 关键函数说明 **`detect_anomalies_global()`** - **功能**: 使用全局背景模型进行检测 - **返回值**: Mahalanobis距离图 **`detect_anomalies_local_square()`** - **功能**: 使用局部正方形窗口进行检测 - **参数**: window_size (窗口大小) - **返回值**: 局部距离图 #### 背景模型类型 - **global**: 使用整个图像作为背景 - **local_row**: 使用行窗口作为背景 - **local_square**: 使用正方形窗口作为背景 - **custom**: 使用外部背景数据 #### 使用示例 ```python from Anomaly_method.RX import RXConfig, RXAnomalyDetector config = RXConfig( input_path="hyperspectral.hdr", background_model='local_square', window_size=5, threshold=10.0 ) detector = RXAnomalyDetector(config) detector.load_data() distance_map = detector.detect_anomalies() detector.save_results() ``` #### 依赖关系说明 - scikit-learn: 协方差估计 - numpy: 数值计算 - scipy: 线性代数 - spectral: 高光谱数据处理 - cv2: 图像处理 ### 4.7 Anomaly_method/squared_loss_probability.py #### 模块功能说明 基于最小二乘自重构的异常检测器,实现完全无监督的异常检测。通过学习数据的自重构模式来识别异常样本。 #### 类和方法列表 | 类名 | 方法名 | 功能描述 | |-----|-------|---------| | `SquaredLossAnomalyConfig` | `__post_init__()` | 配置验证 | | `SquaredLossAnomalyDetector` | `__init__(config)` | 初始化检测器 | | | `load_data()` | 加载高光谱数据 | | | `build_reconstruction_model()` | 构建自重构模型 | | | `detect_anomalies()` | 执行异常检测 | | | `save_results()` | 保存检测结果 | #### 关键函数说明 **`build_reconstruction_model()`** - **功能**: 构建自重构模型 - **支持方法**: linear (线性重构), pca (PCA重构) **`_compute_linear_reconstruction_errors()`** - **功能**: 计算线性重构误差 - **算法**: 使用前n-1个波段预测最后一个波段 **`_compute_pca_reconstruction_errors()`** - **功能**: 计算PCA重构误差 - **算法**: 使用PCA降维重构 #### 使用示例 ```python from Anomaly_method.squared_loss_probability import SquaredLossAnomalyConfig, SquaredLossAnomalyDetector config = SquaredLossAnomalyConfig( input_path="hyperspectral.hdr", reconstruction_method='pca', n_components=10, probability_flag=True ) detector = SquaredLossAnomalyDetector(config) detector.load_data() detector.build_reconstruction_model() predictions, probabilities = detector.detect_anomalies() detector.save_results() ``` #### 依赖关系说明 - scikit-learn: 线性回归和PCA - numpy: 数值计算 - spectral: 高光谱数据处理 ### 4.8 preprocessing_method/Preprocessing.py #### 模块功能说明 数据预处理模块,提供数据清洗、标准化、格式转换等基础预处理功能。 #### 类和方法列表 | 类名 | 方法名 | 功能描述 | |-----|-------|---------| | `DataPreprocessor` | `__init__(config)` | 初始化预处理器 | | | `load_data()` | 加载数据文件 | | | `clean_data()` | 数据清洗和预处理 | | | `normalize_data()` | 数据标准化 | | | `remove_outliers()` | 异常值处理 | | | `save_processed_data()` | 保存处理后的数据 | #### 关键函数说明 **`clean_data()`** - **功能**: 执行完整的数据清洗流程 - **参数**: - `remove_nan`: bool, 是否移除NaN值 - `remove_duplicates`: bool, 是否移除重复行 - `handle_outliers`: bool, 是否处理异常值 - **返回值**: 清洗后的DataFrame - **异常**: ValueError (参数无效) #### 使用示例 ```python from preprocessing_method.Preprocessing import DataPreprocessor preprocessor = DataPreprocessor(data_path="raw_data.csv") cleaned_data = preprocessor.clean_data(remove_nan=True, handle_outliers=True) preprocessor.save_processed_data("cleaned_data.csv") ``` #### 依赖关系说明 - numpy: 数值计算 - pandas: 数据处理 - scipy: 统计函数 - scikit-learn: 数据预处理算法 ### 4.9 Dimensionality_Reduction_method/dimensionality_reduction.py #### 模块功能说明 高光谱数据降维分析模块,提供多种线性、非线性和监督降维算法。 #### 类和方法列表 | 类名 | 方法名 | 功能描述 | |-----|-------|---------| | `DimensionalityReductionConfig` | `__post_init__()` | 配置验证和初始化 | | `HyperspectralDimReduction` | `__init__(config)` | 初始化降维处理器 | | | `load_data()` | 加载高光谱数据 | | | `apply_dim_reduction()` | 执行降维算法 | | | `batch_process()` | 批量降维处理 | | | `get_recommended_methods()` | 获取推荐算法 | | | `save_results()` | 保存降维结果 | #### 关键函数说明 **`apply_dim_reduction()`** - **功能**: 根据配置应用指定的降维算法 - **参数**: 无(使用配置参数) - **返回值**: Tuple[np.ndarray, List[str]] (降维数据, 波段名称) - **异常**: - ValueError: 方法不支持或参数无效 - MemoryError: 数据过大 **`batch_process(methods, n_components_list, output_dir)`** - **功能**: 批量应用多种降维方法 - **参数**: - methods: List[str], 降维方法列表 - n_components_list: List[int], 各方法维度数 - output_dir: str, 输出目录 - **返回值**: Dict, 各方法的处理结果 #### 使用示例 ```python from Dimensionality_Reduction_method.dimensionality_reduction import * config = DimensionalityReductionConfig( input_path="hyperspectral.hdr", method='pca', n_components=5 ) processor = HyperspectralDimReduction(config) processor.load_data() reduced_data, band_names = processor.apply_dim_reduction() ``` #### 依赖关系说明 - scikit-learn: 降维算法实现 - numpy: 数值计算 - scipy: 科学计算 - spectral: ENVI文件处理 - pandas: 数据处理 ### 4.10 segment_method/threshold_Segment.py #### 模块功能说明 图像阈值分割模块,提供多种阈值分割算法用于图像分割。 #### 类和方法列表 | 类名 | 方法名 | 功能描述 | |-----|-------|---------| | `ThresholdSegmentationConfig` | `__post_init__()` | 配置验证 | | `ThresholdSegmenter` | `__init__(config)` | 初始化分割器 | | | `load_data()` | 加载图像数据 | | | `apply_segmentation()` | 执行分割算法 | | | `batch_process()` | 批量分割处理 | | | `save_results()` | 保存分割结果 | #### 关键函数说明 **`apply_segmentation()`** - **功能**: 应用指定的阈值分割算法 - **参数**: 无(使用配置参数) - **返回值**: Tuple[np.ndarray, float] (分割结果, 使用的阈值) - **异常**: ValueError (方法不支持) #### 支持的分割方法 - **fixed**: 固定阈值分割 - **histogram_bimodal**: 直方图双峰法 - **adaptive**: 自适应阈值分割 - **iterative**: 迭代法阈值分割 - **otsu**: Otsu大津法 - **isodata**: ISODATA分割 #### 使用示例 ```python from segment_method.threshold_Segment import * config = ThresholdSegmentationConfig( input_path="image.hdr", band_index=50, method='otsu' ) processor = ThresholdSegmenter(config) processor.load_data() segmented, threshold = processor.apply_segmentation() processor.save_results(segmented, threshold, 'result.dat', 'otsu') ``` #### 依赖关系说明 - opencv-python: 图像处理算法 - numpy: 数值计算 - scipy: 科学计算 - spectral: 高光谱数据处理 ### 4.11 spatial_features_method/shape_feature.py #### 模块功能说明 形状特征分析模块,提供全面的二值图像形状特征提取和分析功能。支持连通域分析、分水岭算法物体分离,以及13种形状特征指标计算。 #### 类和方法列表 | 类名 | 方法名 | 功能描述 | |-----|-------|---------| | `ShapeFeatureConfig` | `__init__()` | 初始化配置参数 | | `ShapeFeatureConfig` | `validate()` | 验证配置参数有效性 | | - | `load_binary_image_from_dat()` | 从ENVI dat文件加载二值图像 | | - | `load_regions_from_shp()` | 从shp文件加载区域信息 | | - | `apply_watershed_segmentation()` | 应用分水岭算法分离物体 | | - | `label_connected_components()` | 连通域标记和分析 | | - | `calculate_shape_features()` | 计算所有形状特征指标 | | - | `save_features_to_csv()` | 保存特征数据到CSV文件 | | - | `save_labeled_image()` | 保存标记后的图像 | | - | `analyze_shape_features()` | 执行完整的形状特征分析流程 | #### 核心功能特性 1. **数据输入支持** - ENVI格式二值图像(.dat + .hdr) - ESRI Shapefile格式矢量数据 - 自动格式检测和参数解析 2. **连通域分析** - 4连通和8连通区域标记 - 最小区域面积过滤 - 区域统计信息提取 3. **分水岭物体分离** - 基于距离变换的种子点检测 - 可调节的最小距离参数 - 自动粘连物体分离 4. **形状特征指标** | 特征名称 | 公式/描述 | 应用场景 | |---------|----------|---------| | Area | 像素总数 | 区域大小测量 | | Perimeter | 边界长度 | 形状复杂度 | | Circularity | 4π×面积/周长² | 圆形程度评估 | | Rectangularity | 面积/外接矩形面积 | 矩形相似度 | | Aspect Ratio | 宽度/高度 | 形状伸长程度 | | Compactness | 周长²/面积 | 形状紧凑度 | | Eccentricity | 椭圆离心率 | 形状不对称性 | | Hu Moments | 7个不变矩 | 平移/旋转/缩放不变特征 | | Convexity | 面积/凸包面积 | 凹凸程度 | | Solidity | 面积/凸包面积 | 形状实体度 | | Contour Moments | 轮廓矩 | 边界形状描述 | #### 配置参数说明 ```python @dataclass class ShapeFeatureConfig: # 输入数据设置 input_type: str = 'dat' # 'dat' 或 'shp' dat_file_path: str = None # dat文件路径 hdr_file_path: str = None # 对应的hdr文件路径 shp_file_path: str = None # shp文件路径 band_index: int = 0 # 处理的波段索引 # 连通域处理参数 connectivity: int = 8 # 连通性:4或8 min_area: int = 10 # 最小区域面积 use_watershed: bool = False # 是否使用分水岭算法 # 分水岭算法参数 watershed_min_distance: int = 10 # 局部最大值最小距离 # 输出设置 output_dir: str = "output" output_csv: bool = True # 输出CSV文件 save_labeled_image: bool = False # 保存标记图像 ``` #### 使用示例 ```python # 基本使用示例 from spatial_features_method.shape_feature import ShapeFeatureConfig, analyze_shape_features # 配置参数 config = ShapeFeatureConfig() config.input_type = 'dat' config.dat_file_path = "segmented_data.dat" config.hdr_file_path = "segmented_data.hdr" config.use_watershed = True # 启用分水岭算法 config.min_area = 50 # 过滤小区域 # 执行分析 features_df, labeled_image = analyze_shape_features(config) # 查看结果 print(f"发现 {len(features_df)} 个区域") print("特征列表:", features_df.columns.tolist()) ``` #### 输出文件格式 1. **CSV文件**: 形状特征数据表格 - 每行对应一个连通域 - 每列对应一个特征指标 2. **JSON文件**: 轮廓坐标数据 - 包含每个区域的边界像素坐标 - 格式: `{"region_1_coords": [[x1,y1], [x2,y2], ...]}` 3. **ENVI格式**: 标记图像 - .dat文件: 标记后的分割结果 - .hdr文件: ENVI头文件,包含元数据 #### 依赖关系说明 - scikit-image: 连通域分析和形状特征计算 - opencv-python: 图像处理和可视化 - numpy: 数值计算 - pandas: 数据处理和CSV输出 - spectral: ENVI格式数据读取 - geopandas: Shapefile数据读取(可选) - scipy: 科学计算和距离变换 #### 性能优化建议 - 对于大图像,适当调整`min_area`参数过滤小区域 - 分水岭算法对计算资源要求较高,建议对复杂场景使用 - 特征计算支持并行处理,可扩展到多核CPU ### 4.12 edge_detect_method/edge_detect.py #### 模块功能说明 边缘检测模块,提供多种经典和现代边缘检测算法。 #### 类和方法列表 | 类名 | 方法名 | 功能描述 | |-----|-------|---------| | `EdgeDetectionConfig` | `__post_init__()` | 配置验证 | | `EdgeDetector` | `__init__(config)` | 初始化检测器 | | | `load_data()` | 加载图像数据 | | | `apply_edge_detection()` | 执行边缘检测 | | | `batch_process()` | 批量检测处理 | | | `save_results()` | 保存检测结果 | #### 支持的检测方法 - **sobel**: Sobel算子 - **scharr**: Scharr算子 - **laplacian**: Laplacian算子 - **log**: Laplacian of Gaussian - **canny**: Canny算子 #### 关键参数说明 | 参数 | 类型 | 默认值 | 说明 | |-----|------|-------|------| | `method` | str | 'canny' | 检测算法选择 | | `canny_min_threshold` | int | 100 | Canny最小阈值 | | `canny_max_threshold` | int | 200 | Canny最大阈值 | | `use_blur` | bool | False | 是否预先模糊 | | `log_sigma` | float | 1.0 | LoG高斯标准差 | #### 使用示例 ```python from edge_detect_method.edge_detect import * config = EdgeDetectionConfig( input_path="image.hdr", band_index=30, method='canny', canny_min_threshold=50, canny_max_threshold=150, use_blur=True ) detector = EdgeDetector(config) detector.load_data() edges, info = detector.apply_edge_detection() detector.save_results(edges, info, 'edges.dat', 'canny') ``` #### 依赖关系说明 - opencv-python: 图像处理算法 - scipy: LoG算法实现 - numpy: 数值计算 - spectral: 高光谱数据处理 ### 4.13 spatial_features_method/get_glcm.py #### 模块功能说明 纹理特征分析模块,基于灰度共生矩阵(GLCM)提供9种经典纹理特征提取。支持滑动窗口分析、多尺度多角度GLCM计算,以及完整的纹理特征统计。 #### 函数列表 | 函数名 | 参数 | 返回值 | 功能描述 | |-------|------|-------|---------| | `calcu_glcm()` | img, vmin, vmax, nbit, slide_window, step, angle | GLCM数组 | 计算灰度共生矩阵 | | `calcu_glcm_mean()` | glcm, nbit | 均值矩阵 | 计算GLCM均值特征 | | `calcu_glcm_variance()` | glcm, nbit | 方差矩阵 | 计算GLCM方差特征 | | `calcu_glcm_homogeneity()` | glcm, nbit | 同质性矩阵 | 计算GLCM同质性特征 | | `calcu_glcm_contrast()` | glcm, nbit | 对比度矩阵 | 计算GLCM对比度特征 | | `calcu_glcm_dissimilarity()` | glcm, nbit | 相异性矩阵 | 计算GLCM相异性特征 | | `calcu_glcm_entropy()` | glcm, nbit | 熵矩阵 | 计算GLCM熵特征 | | `calcu_glcm_energy()` | glcm, nbit | 能量矩阵 | 计算GLCM能量特征 | | `calcu_glcm_correlation()` | glcm, nbit | 相关性矩阵 | 计算GLCM相关性特征 | | `calcu_glcm_Auto_correlation()` | glcm, nbit | 自相关矩阵 | 计算GLCM自相关特征 | #### 核心功能特性 1. **GLCM计算** - 支持多尺度距离参数(step) - 支持多角度分析(angle) - 灰度级压缩(nbit参数控制) - 滑动窗口处理(slide_window) 2. **纹理特征指标** | 特征名称 | 公式/定义 | 物理意义 | |---------|----------|---------| | **均值 (Mean)** | `Σ(i × P(i,j))` | 纹理灰度平均水平 | | **方差 (Variance)** | `Σ((i-μ)² × P(i,j))` | 纹理灰度变化程度 | | **同质性 (Homogeneity)** | `Σ(P(i,j)/(1+(i-j)²))` | 纹理局部均匀程度 | | **对比度 (Contrast)** | `Σ((i-j)² × P(i,j))` | 纹理深度和清晰度 | | **相异性 (Dissimilarity)** | `Σ(\|i-j\| × P(i,j))` | 纹理灰度差异程度 | | **熵 (Entropy)** | `-Σ(P(i,j) × log(P(i,j)))` | 纹理复杂度/随机性 | | **能量 (Energy)** | `Σ(P(i,j)²)` | 纹理均匀度和重复度 | | **相关性 (Correlation)** | `Σ((i-μ)(j-μ)P(i,j)/σ²)` | 纹理线性相关程度 | | **自相关 (Auto-correlation)** | `Σ(i × j × P(i,j))` | 纹理空间相关性 | #### 技术实现细节 1. **灰度级压缩** ```python bins = np.linspace(mi, ma+1, nbit+1) img1 = np.digitize(img, bins) - 1 ``` - 将原始灰度范围压缩到nbit级 - 提高GLCM计算效率和特征鲁棒性 2. **滑动窗口处理** ```python img2 = cv2.copyMakeBorder(img1, floor(slide_window/2), ...) patch = image_patch(img2, slide_window, h, w) ``` - 边界填充确保窗口完整性 - 为每个像素位置计算局部GLCM 3. **GLCM构建** ```python glcm[:, :, :, :, i, j] = graycomatrix(patch[:, :, i, j], step, angle, levels=nbit) ``` - 使用skimage的graycomatrix函数 - 支持多距离多角度分析 #### 参数配置说明 ```python # 基本参数配置 vmin, vmax = 0, 255 # 灰度范围 nbit = 64 # 灰度级数 slide_window = 7 # 滑动窗口大小 step = [1, 2, 4] # 距离参数 angle = [0, np.pi/4, np.pi/2, np.pi*3/4] # 角度参数 ``` #### 使用示例 ```python import numpy as np from spatial_features_method.get_glcm import calcu_glcm, calcu_glcm_energy # 加载图像 img = np.random.randint(0, 256, (100, 100), dtype=np.uint8) # 计算GLCM glcm = calcu_glcm(img, vmin=0, vmax=255, nbit=64, slide_window=7, step=[2], angle=[0]) # 提取纹理特征 energy = calcu_glcm_energy(glcm, nbit=64) contrast = calcu_glcm_contrast(glcm, nbit=64) homogeneity = calcu_glcm_homogeneity(glcm, nbit=64) print(f"能量特征形状: {energy.shape}") print(f"对比度特征形状: {contrast.shape}") ``` #### 性能优化建议 1. **参数选择** - nbit=64:平衡计算效率和特征分辨率 - slide_window=7:适用于大多数纹理分析 - step=[1,2]:覆盖近邻和稍远距离 2. **内存管理** - 大图像建议分块处理 - GLCM数据结构较大,注意内存使用 3. **计算效率** - 减少不必要的角度参数 - 根据应用需求选择特征子集 #### 依赖关系说明 - scikit-image: GLCM计算核心库 - opencv-python: 图像处理和边界填充 - numpy: 数值计算和数组操作 ### 4.14 classfication_method/classfication.py #### 模块功能说明 高光谱图像分类模块,提供多种机器学习分类算法和完整的训练评估流程。 #### 类和方法列表 | 类名 | 方法名 | 功能描述 | |-----|-------|---------| | `ClassificationConfig` | `__post_init__()` | 配置验证 | | `HyperspectralClassifier` | `__init__(config)` | 初始化分类器 | | | `load_training_data()` | 加载训练数据 | | | `train_models()` | 训练多个模型 | | | `evaluate_models()` | 模型评估 | | | `predict_image()` | 图像预测 | | | `save_models()` | 保存模型 | #### 支持的分类算法 - SVM, 随机森林, KNN, 逻辑回归 - XGBoost, LightGBM, CatBoost - LDA, QDA, 朴素贝叶斯 - 神经网络分类器 #### 关键函数说明 **`train_models()`** - **功能**: 训练指定的分类模型 - **参数**: - model_names: List[str], 模型名称列表 - tune_hyperparams: bool, 是否调参 - **返回值**: Dict, 训练好的模型字典 - **异常**: ValueError (模型不支持) #### 使用示例 ```python from classfication_method.classfication import * config = ClassificationConfig( training_data="training.csv", label_column="class", models=['svm', 'rf', 'xgboost'] ) classifier = HyperspectralClassifier(config) classifier.load_training_data() models = classifier.train_models() results = classifier.evaluate_models(models) ``` #### 依赖关系说明 - scikit-learn: 机器学习算法 - xgboost: 梯度提升 - lightgbm: 快速梯度提升 - catboost: 类别特征处理 - numpy, pandas: 数据处理 ### 4.15 rgression_method/regression.py #### 模块功能说明 回归分析模块,提供多种回归算法用于连续值预测。 #### 类和方法列表 | 类名 | 方法名 | 功能描述 | |-----|-------|---------| | `RegressionConfig` | `__post_init__()` | 配置验证 | | `RegressionAnalyzer` | `__init__(config)` | 初始化回归器 | | | `load_data()` | 加载数据 | | | `train_models()` | 训练回归模型 | | | `evaluate_models()` | 模型评估 | | | `predict()` | 预测新数据 | | | `save_models()` | 保存模型 | #### 支持的回归算法 - 线性回归, 岭回归, LASSO, 弹性网络 - SVR, 随机森林回归, 梯度提升回归 - KNN回归, 高斯过程回归 - XGBoost, LightGBM回归 #### 使用示例 ```python from rgression_method.regression import * config = RegressionConfig( data_path="data.csv", label_column="chlorophyll", models=['linear', 'ridge', 'xgboost'] ) analyzer = RegressionAnalyzer(config) analyzer.load_data() models = analyzer.train_models() results = analyzer.evaluate_models(models) ``` #### 依赖关系说明 - scikit-learn: 回归算法 - xgboost, lightgbm: 高级回归 - numpy, pandas: 数据处理 - scipy: 统计函数 ### 4.16 cluster_method/cluster.py #### 模块功能说明 聚类分析模块,提供多种无监督聚类算法。 #### 类和方法列表 | 类名 | 方法名 | 功能描述 | |-----|-------|---------| | `ClusteringConfig` | `__post_init__()` | 配置验证 | | `HyperspectralClusterer` | `__init__(config)` | 初始化聚类器 | | | `load_data()` | 加载数据 | | | `perform_clustering()` | 执行聚类 | | | `evaluate_clustering()` | 聚类评估 | | | `visualize_clusters()` | 聚类可视化 | #### 支持的聚类算法 - K-Means, MiniBatchKMeans - 层次聚类, DBSCAN - 高斯混合模型, 均值漂移 - 谱聚类, 亲和力传播 #### 使用示例 ```python from cluster_method.cluster import * config = ClusteringConfig( data_path="data.csv", algorithm='kmeans', n_clusters=5 ) clusterer = HyperspectralClusterer(config) clusterer.load_data() labels = clusterer.perform_clustering() metrics = clusterer.evaluate_clustering(labels) ``` #### 依赖关系说明 - scikit-learn: 聚类算法 - numpy, pandas: 数据处理 - matplotlib: 可视化 ### 4.17 Feature_Selection_method/feture_select.py #### 模块功能说明 特征选择模块,提供多种特征重要性评估和选择方法。 #### 类和方法列表 | 类名 | 方法名 | 功能描述 | |-----|-------|---------| | `FeatureSelector` | `__init__(config)` | 初始化选择器 | | | `select_features()` | 执行特征选择 | | | `rank_features()` | 特征重要性排序 | | | `transform_data()` | 转换数据到选择特征 | #### 支持的方法 - 过滤法: 方差阈值, 相关系数, 互信息 - 包裹法: 递归特征消除, 顺序特征选择 - 嵌入法: LASSO, 随机森林重要性 #### 使用示例 ```python from Feature_Selection_method.feture_select import * selector = FeatureSelector(method='rf_importance', k=50) selected_features = selector.select_features(X, y) X_selected = selector.transform_data(X) ``` #### 依赖关系说明 - scikit-learn: 特征选择算法 - numpy: 数值计算 ### 4.18 fliter_method 模块 #### Smooth_filter.py **功能**: 空间域图像滤波 - 支持滤波: 均值, 高斯, 中值, 双边 - 参数: 核大小, 标准差等 #### morphological_fliter.py **功能**: 形态学图像处理 - 操作: 腐蚀, 膨胀, 开闭运算 - 结构元素: 矩形, 椭圆, 十字 #### 使用示例 ```python from fliter_method.Smooth_filter import ImageFilter filter = ImageFilter(method='gaussian', kernel_size=5, sigma=1.0) filtered_image = filter.apply_filter(image) ``` ### 4.19 spectral_index_method/spectral_index.py #### 模块功能说明 光谱指数计算模块,提供丰富的植被、水体、土壤等指数计算。 #### 类和方法列表 | 类名 | 方法名 | 功能描述 | |-----|-------|---------| | `SpectralIndexCalculator` | `__init__(config)` | 初始化计算器 | | | `calculate_index()` | 计算指定指数 | | | `batch_calculate()` | 批量计算多个指数 | | | `save_results()` | 保存计算结果 | #### 支持的指数 - **植被指数**: NDVI, EVI, ARVI, SAVI - **水体指数**: NDWI, MNDWI - **土壤指数**: NDSI, BI - **自定义指数**: 用户定义公式 #### 使用示例 ```python from spectral_index_method.spectral_index import * calculator = SpectralIndexCalculator() ndvi = calculator.calculate_index('NDVI', nir_band, red_band) results = calculator.batch_calculate(['NDVI', 'EVI', 'NDWI'], spectral_data) ``` #### 依赖关系说明 - numpy: 数值计算 - pandas: 数据处理 ### 4.20 color_method/DeltaE.py #### 模块功能说明 Delta E* 色差计算工具,支持多种颜色差异计算方法,用于分析图像中像素与标准色库之间的颜色差异。提供完整的色差计算、可视化和分析功能。 #### 类和方法列表 | 类名 | 方法名 | 功能描述 | |-----|-------|---------| | `DeltaEMethod` | `to_colour_method()` | 内部方法映射到colour库方法 | | `ColorData` | `__init__()` | 颜色数据容器初始化 | | | `from_array()` | 从数组创建ColorData对象 | | `LabDataValidator` | `validate_lab_range()` | LAB数据范围验证 | | | `validate_data_shape()` | 数据形状兼容性验证 | | `ColorStandardManager` | `load_from_csv()` | 加载标准色CSV文件 | | | `get_standard_colors()` | 获取标准色数据 | | `DeltaECalculator` | `__init__(method)` | 初始化色差计算器 | | | `calculate()` | 计算两个LAB颜色集之间的Delta E | | | `calculate_image_vs_standards()` | 计算图像与标准色的色差 | | | `calculate_pairwise()` | 计算两组颜色的配对Delta E | | `EnviFileHandler` | `load_image()` | 加载ENVI格式LAB图像 | | | `save_color_data()` | 保存颜色数据到文件 | | `DeltaEVisualizer` | `create_heatmap()` | 创建Delta E热图 | | | `create_delta_e_histogram()` | 创建Delta E分布直方图 | | `DeltaEApp` | `run()` | 运行主应用程序 | #### 核心功能特性 1. **色差计算方法** - **CIE76**: 欧几里德距离,简单快速 - **CIE94**: 改进的色差公式,考虑明度影响 - **CIEDE2000**: 最新的色差标准,最高准确性 2. **输入输出格式** - 输入:LAB三波段ENVI图像 + 标准色CSV文件 - 输出:Delta E多波段图像、CSV摘要、PNG可视化 3. **标准色管理** - CSV格式标准色库加载 - 类别分组和索引选择 - 自动数据验证和清理 4. **可视化功能** - 多标准色热图展示 - Delta E分布直方图 - 统计信息标注 #### 关键函数说明 **`calculate_image_vs_standards()`** - **功能**: 计算图像中每个像素与每个标准色的Delta E - **参数**: - `image_data`: 图像LAB数据 (ColorData对象) - `standards`: 标准色数据 (ColorData对象) - `use_progress_bar`: 是否显示进度条 - **返回值**: Delta E图像数组 (height, width, n_standards) - **异常**: ValueError (数据格式错误) **`calculate_pairwise()`** - **功能**: 计算两组颜色之间的配对Delta E - **参数**: - `colors1`: 第一组颜色数据 - `colors2`: 第二组颜色数据(可选) - **返回值**: 包含Delta E结果的pandas DataFrame #### 使用示例 ```python from color_method.DeltaE import * # 直接函数调用方式 delta_e_image = calculate_delta_e_image( image_path="lab_image.hdr", standards_path="standards.csv", output_path="delta_e_result.dat", method="CIEDE2000", create_heatmap=True, create_histogram=True ) # 配对比较方式 result_df = calculate_delta_e_pairwise( standards_path="standards.csv", output_path="pairwise_result.csv", reference_range="0-5", target_range="6-10", create_heatmap=True ) ``` #### 依赖关系说明 - colour-science: 色差计算核心库 - numpy: 数值计算 - pandas: 数据处理和结果输出 - spectral: ENVI文件格式处理 - matplotlib: 可视化输出 ### 4.21 color_method/spectral2cie2.py #### 模块功能说明 光谱到颜色转换工具,将高光谱反射率数据转换为CIE颜色空间的三刺激值。支持多种标准光源、观察者和输出颜色空间,提供完整的颜色科学计算功能。 #### 类和方法列表 | 类名 | 方法名 | 功能描述 | |-----|-------|---------| | `SpectralToColorConverter` | `__init__()` | 初始化转换器 | | | `_setup_color_space()` | 设置颜色空间参数 | | | `load_csv_data()` | 加载CSV光谱数据 | | | `load_envi_data()` | 加载ENVI高光谱数据 | | | `spectral_to_xyz()` | 光谱转XYZ(自定义实现) | | | `spectral_to_xyz_colour()` | 光谱转XYZ(colour库) | | | `convert_color_space()` | 转换为指定颜色空间 | | | `xyz_to_xyy()` | XYZ转xyY | | | `xyz_to_lab()` | XYZ转L*a*b* | | | `xyz_to_lch()` | XYZ转L*C*h* | | | `process_file()` | 处理单个文件 | | | `save_color_data()` | 保存颜色数据 | #### 核心功能特性 1. **光谱数据输入** - CSV格式:波长-反射率表格数据 - ENVI格式:高光谱图像数据 - 自动格式检测和数据预处理 2. **标准条件设置** - **光源**: D65, D50, A, F2, F7, F11 - **观察者**: CIE 1931 2°, CIE 1964 10° - **输出空间**: XYZ, xyY, Lab, LCH 3. **颜色计算方法** - 自定义实现:基于颜色匹配函数的积分计算 - colour库实现:使用内置的sd_to_XYZ函数 - 批处理支持:高效处理大量光谱数据 4. **数据预处理** - 波长插值和外推 - 反射率范围裁剪 - 自动光谱范围确定 #### 关键函数说明 **`spectral_to_xyz()`** - **功能**: 使用自定义算法将光谱转换为XYZ - **参数**: - `wavelengths`: 波长数组 (nm) - `reflectances`: 反射率数组 (..., wavelengths) - **返回值**: XYZ三刺激值数组 (..., 3) - **算法**: 基于矩形积分的颜色匹配函数计算 **`spectral_to_xyz_colour()`** - **功能**: 使用colour库进行光谱到XYZ转换 - **参数**: 同上 - **返回值**: 同上 - **算法**: 使用colour库的sd_to_XYZ函数 #### 使用示例 ```python from color_method.spectral2cie2 import SpectralToColorConverter # 创建转换器 converter = SpectralToColorConverter( illuminant='D65', observer='2°', color_space='Lab' ) # 处理ENVI文件 color_data = converter.process_file( input_path="hyperspectral.hdr", output_path="color_result.dat", output_format='dat', use_colour_library=True ) # 处理CSV数据 wavelengths, reflectances = converter.load_csv_data("spectra.csv") xyz_values = converter.spectral_to_xyz(wavelengths, reflectances) ``` #### 依赖关系说明 - colour-science: 颜色科学计算核心库 - numpy: 数值计算 - pandas: CSV数据处理 - spectral: ENVI格式处理 - scipy: 插值计算 ### 4.22 color_method/XYZ2RGB.py #### 模块功能说明 XYZ到RGB颜色空间转换工具,将CIE XYZ三刺激值转换为指定的RGB颜色空间。支持多种RGB工作空间、伽马校正方法和输出数据类型,提供完整的颜色空间转换功能。 #### 类和方法列表 | 类名 | 方法名 | 功能描述 | |-----|-------|---------| | `RGBColorSpace` | - | RGB色彩空间枚举 | | `GammaMethod` | - | 伽马校正方法枚举 | | `OutputDataType` | - | 输出数据类型枚举 | | `XYZ2RGBConverter` | `__init__()` | 初始化转换器 | | | `convert_xyz_to_rgb()` | 执行XYZ到RGB转换 | | | `_apply_gamma_to_rgb()` | 应用伽马校正 | | | `_convert_to_output_dtype()` | 转换为输出数据类型 | | `EnviFileHandler` | `load_xyz_image()` | 加载XYZ ENVI图像 | | | `save_rgb_image()` | 保存RGB BIP图像 | | `XYZ2RGBApp` | `run()` | 运行主应用程序 | #### 核心功能特性 1. **RGB色彩空间支持** - **标准空间**: sRGB, Adobe RGB (1998), DCI-P3 - **广播空间**: ITU-R BT.709, BT.2020 - **专业空间**: ProPhoto RGB, ACES2065-1, ACEScg - **传统空间**: Apple RGB, PAL/SECAM, NTSC (1953) 2. **伽马校正方法** - **标准曲线**: sRGB, BT.709 - **幂函数**: gamma 2.2, gamma 1.8, gamma 2.4 - **专业曲线**: L*, BT.1886 (HDR) - **HDR曲线**: ST 2084 (PQ), HLG 3. **输出数据类型** - **标准类型**: uint8, uint16, float32, float64 - **扩展类型**: uint10, uint12, int8, int16, float16 4. **文件格式支持** - 输入:三波段XYZ ENVI格式 (.dat/.hdr) - 输出:三波段RGB BIP格式 (.bip/.hdr) #### 关键函数说明 **`convert_xyz_to_rgb()`** - **功能**: 执行完整的XYZ到RGB转换流程 - **参数**: - `xyz_data`: XYZ数据数组 (..., 3) - **返回值**: RGB数据数组 (..., 3) - **处理流程**: XYZ→RGB线性→伽马校正→数据类型转换 **`save_rgb_image()`** - **功能**: 将RGB数据保存为BIP格式ENVI文件 - **参数**: - `rgb_data`: RGB数据数组 - `output_path`: 输出文件路径 - `rgb_space`: RGB色彩空间名称 - **输出格式**: BIP (Band Interleaved by Pixel) #### 使用示例 ```python from color_method.XYZ2RGB import convert_xyz_to_rgb # 直接函数调用 rgb_data = convert_xyz_to_rgb( input_path="xyz_image.dat", output_path="rgb_image.bip", rgb_space="Adobe RGB (1998)", gamma_method="sRGB", output_dtype="uint8" ) # 命令行使用 # python XYZ2RGB.py --input xyz_image.dat --output rgb_image.bip --rgb-space "Adobe RGB (1998)" ``` #### 依赖关系说明 - colour-science: 颜色空间转换核心库 - numpy: 数值计算 - spectral: ENVI文件处理 - GDAL: 高级文件保存(可选) ### 4.23 color_method/test.py #### 模块功能说明 颜色科学计算测试模块,提供colour-science库的基本使用示例和测试代码。主要用于验证颜色空间转换、色差计算等功能的正确性。 #### 主要测试内容 1. **白点计算测试** - D65光源白点计算和验证 - 使用CCS_ILLUMINANTS字典获取标准白点 - 使用sd_to_XYZ函数计算光源白点 2. **XYZ到Lab转换测试** - 单一样本转换测试 - 多样本批量转换测试 - 不同光源条件下的转换比较 3. **颜色科学基础验证** - 标准观察者颜色匹配函数验证 - 光谱功率分布数据验证 - 颜色空间转换公式验证 #### 使用示例 ```python # 运行测试代码验证colour库功能 import colour # D65光源白点计算 d65_xy = colour.CCS_ILLUMINANTS['CIE 1931 2 Degree Standard Observer']['D65'] print(f"D65 white point: {d65_xy}") # XYZ to Lab conversion test xyz_sample = np.array([0.4124, 0.2126, 0.0193]) lab_result = colour.XYZ_to_Lab(xyz_sample) print(f"XYZ to Lab: {lab_result}") ``` #### 依赖关系说明 - colour-science: 颜色科学计算库 - numpy: 数值计算 --- ## 总结 本文档提供了高光谱图像分类与分析工具包的完整技术说明,包括: 1. **项目概述**: 背景、目标、特色功能 2. **核心特性**: 详细的功能特性和技术栈 3. **系统架构**: Mermaid图表展示的系统结构 4. **模块说明**: 19个功能模块的详细介绍 5. **数据流程**: 完整的数据处理流程图 6. **安装部署**: 详细的安装和配置指南 7. **API文档**: 完整的接口说明和参数文档 8. **使用示例**: 从基础到高级的各种使用场景 9. **配置说明**: 配置系统的详细说明 10. **维护指南**: 代码规范、测试策略、版本管理 每个模块都包含了详细的类和方法列表、关键函数说明、使用示例和依赖关系。文档采用专业的技术写作格式,包含代码片段、表格和图表,便于理解和使用。 --- **文档版本**: 1.1 **最后更新**: 2025年12月 **维护者**: 开发团队 **许可证**: MIT License