Commit ·
68df6d6
0
Parent(s):
Duplicate from lyj-flower/PaleVision
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +37 -0
- .gitignore +18 -0
- LICENSE +21 -0
- README.md +131 -0
- configs/lib_hsi_v2.yaml +53 -0
- configs/mars.yaml +26 -0
- configs/mhsi.yaml +26 -0
- configs/minneapple.yaml +44 -0
- configs/modid.yaml +26 -0
- dataloader/Data_Generate.py +86 -0
- dataloader/Mars.py +176 -0
- dataloader/__init__.py +0 -0
- dataloader/argument.py +64 -0
- dataloader/lib_hsi.py +322 -0
- dataloader/minneapple.py +195 -0
- dataloader/minneapple_ninja.py +149 -0
- dataloader/modid.py +88 -0
- datasets/.gitkeep +0 -0
- docs/.nojekyll +1 -0
- docs/assets/favicon.png +0 -0
- docs/assets/palevision-fish.png +3 -0
- docs/assets/thumbnail.jpg +3 -0
- docs/index.html +143 -0
- encoder_swap_exp.py +238 -0
- lib_hsi_exp_v2.py +379 -0
- mars_exp.py +188 -0
- mhsi_exp.py +220 -0
- minneapple_det_count_exp.py +224 -0
- minneapple_exp.py +204 -0
- models/HSI_to_RGB/Mars3.py +44 -0
- models/HSI_to_RGB/__init__.py +0 -0
- models/HSI_to_RGB/evpl_factory.py +45 -0
- models/HSI_to_RGB/invertible_isp_model/__init__.py +1 -0
- models/HSI_to_RGB/invertible_isp_model/loss.py +14 -0
- models/HSI_to_RGB/invertible_isp_model/model.py +152 -0
- models/HSI_to_RGB/invertible_isp_model/modules.py +279 -0
- models/HSI_to_RGB/invertible_isp_model/utils.py +25 -0
- models/HSI_to_RGB/lib_hsi_EVPL.py +205 -0
- models/HSI_to_RGB/mhsi_EVPL.py +43 -0
- models/HSI_to_RGB/mhsi_EVPL_ablation.py +531 -0
- models/HSI_to_RGB/minneapple_EVPL.py +97 -0
- models/HSI_to_RGB/modid_EVPL.py +45 -0
- models/HSI_to_RGB/modid_EVPL_ablation.py +539 -0
- models/HSI_to_RGB/multi_opsin_evpl.py +304 -0
- models/HSI_to_RGB/rgb_opsin.py +48 -0
- models/__init__.py +0 -0
- models/backbone/__init__.py +0 -0
- models/backbone/encoder_factory.py +92 -0
- models/backbone/mix_transformer.py +311 -0
- models/decoder/__init__.py +0 -0
.gitattributes
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
docs/assets/palevision-fish.png filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
docs/assets/thumbnail.jpg filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.py[cod]
|
| 3 |
+
*.egg-info/
|
| 4 |
+
.eggs/
|
| 5 |
+
dist/
|
| 6 |
+
build/
|
| 7 |
+
.env
|
| 8 |
+
.venv/
|
| 9 |
+
.idea/
|
| 10 |
+
.vscode/
|
| 11 |
+
work_dir/**
|
| 12 |
+
!work_dir/.gitkeep
|
| 13 |
+
datasets/**
|
| 14 |
+
!datasets/.gitkeep
|
| 15 |
+
*.log
|
| 16 |
+
*.npy
|
| 17 |
+
*.npz
|
| 18 |
+
.DS_Store
|
LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2026 PaleVision authors
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
README.md
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# PaleVision
|
| 2 |
+
|
| 3 |
+
Official implementation of **Paleoinspired Vision: From Exploring Colour Vision Evolution to Inspiring Camera Design**, accepted at **NeurIPS 2026**.
|
| 4 |
+
|
| 5 |
+
[Project website](https://luyijie-research.github.io/PaleVision/) · [Code](https://github.com/luyijie-research/PaleVision) · [Weights](https://huggingface.co/lyj-flower/PaleVision)
|
| 6 |
+
|
| 7 |
+
PaleVision models opsin spectral responses with learnable evolutionary visual perception layers (EVPL) and trains semantic segmentation on hyperspectral imagery.
|
| 8 |
+
|
| 9 |
+
## Structure
|
| 10 |
+
|
| 11 |
+
```
|
| 12 |
+
configs/ experiment configs
|
| 13 |
+
dataloader/ dataset loaders
|
| 14 |
+
models/ EVPL, encoders, SegFormer head
|
| 15 |
+
util/ training helpers
|
| 16 |
+
weights/ SOTA weights (download; not stored in git)
|
| 17 |
+
datasets/ put datasets here (not shipped)
|
| 18 |
+
work_dir/ logs and checkpoints (not shipped)
|
| 19 |
+
```
|
| 20 |
+
|
| 21 |
+
## Install
|
| 22 |
+
|
| 23 |
+
```bash
|
| 24 |
+
conda create -n palevision python=3.10 -y
|
| 25 |
+
conda activate palevision
|
| 26 |
+
pip install -r requirements.txt
|
| 27 |
+
```
|
| 28 |
+
|
| 29 |
+
Install a CUDA build of PyTorch that matches your driver, then install `mmcv` for your torch/cuda combo if needed.
|
| 30 |
+
|
| 31 |
+
## Data layout (Mars example)
|
| 32 |
+
|
| 33 |
+
```
|
| 34 |
+
datasets/Mars/MSL/train/{img,hsi,label}
|
| 35 |
+
datasets/Mars/MSL/test/{img,hsi,label}
|
| 36 |
+
```
|
| 37 |
+
|
| 38 |
+
`hsi` files are HDF5 with a `cube` dataset of shape `[31, H, W]`.
|
| 39 |
+
|
| 40 |
+
## Train (Mars)
|
| 41 |
+
|
| 42 |
+
```bash
|
| 43 |
+
torchrun --nproc_per_node=1 mars_exp.py \
|
| 44 |
+
--config configs/mars.yaml \
|
| 45 |
+
--workdir work_dir/mars \
|
| 46 |
+
--train_path datasets/Mars/MSL/train \
|
| 47 |
+
--val_path datasets/Mars/MSL/test \
|
| 48 |
+
--encoder_type mit_b0
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
Multi-GPU:
|
| 52 |
+
|
| 53 |
+
```bash
|
| 54 |
+
torchrun --nproc_per_node=2 mars_exp.py \
|
| 55 |
+
--config configs/mars.yaml \
|
| 56 |
+
--workdir work_dir/mars \
|
| 57 |
+
--train_path datasets/Mars/MSL/train \
|
| 58 |
+
--val_path datasets/Mars/MSL/test
|
| 59 |
+
```
|
| 60 |
+
|
| 61 |
+
Smoke check (few steps, small resolution):
|
| 62 |
+
|
| 63 |
+
```bash
|
| 64 |
+
torchrun --nproc_per_node=1 mars_exp.py \
|
| 65 |
+
--config configs/mars.yaml \
|
| 66 |
+
--workdir work_dir/mars_smoke \
|
| 67 |
+
--train_path datasets/Mars/MSL/train \
|
| 68 |
+
--val_path datasets/Mars/MSL/test \
|
| 69 |
+
--batch_size 1 \
|
| 70 |
+
--input_size 128 \
|
| 71 |
+
--max_steps 3 \
|
| 72 |
+
--skip_val \
|
| 73 |
+
--num_workers 2
|
| 74 |
+
```
|
| 75 |
+
|
| 76 |
+
Other entry points: `modid_exp.py`, `mhsi_exp.py`, `lib_hsi_exp_v2.py`, `minneapple_exp.py`, `encoder_swap_exp.py`, `minneapple_det_count_exp.py`.
|
| 77 |
+
|
| 78 |
+
Encoder swap on MODID or MHSI:
|
| 79 |
+
|
| 80 |
+
```bash
|
| 81 |
+
torchrun --nproc_per_node=1 encoder_swap_exp.py \
|
| 82 |
+
--dataset modid \
|
| 83 |
+
--encoder twins_svt_small \
|
| 84 |
+
--opsin_mode free \
|
| 85 |
+
--config configs/modid.yaml \
|
| 86 |
+
--workdir work_dir/modid_twins_free
|
| 87 |
+
```
|
| 88 |
+
|
| 89 |
+
## SOTA weights
|
| 90 |
+
|
| 91 |
+
Released weights keep only module parameters. Optimizer state, epoch counters, and training hyperparameters are not included.
|
| 92 |
+
|
| 93 |
+
| File | Setting | Reported score |
|
| 94 |
+
| --- | --- | --- |
|
| 95 |
+
| `weights/modid_twins_svt_small_free.pth` | MODID, Twins-SVT-Small, FreeConv | mIoU 0.6006 |
|
| 96 |
+
| `weights/mhsi_pvt_v2_b2_free.pth` | MHSI, PVT-v2-B2, FreeConv | mIoU 0.5727 |
|
| 97 |
+
| `weights/lib_hsi.pth` | LIB-HSI, MiT-B3, 3-opsin EVPL with a 2-to-3 projection | mIoU 0.3407 |
|
| 98 |
+
| `weights/minneapple.pth` | MinnApple segmentation, opsin evolve | mIoU 0.4845 |
|
| 99 |
+
| `weights/minneapple_detection.pth` | MinnApple detection, fixed opsin | AP@50 0.3105 |
|
| 100 |
+
| `weights/minneapple_counting.pth` | MinnApple counting, trainable opsin | MAE 2.446 |
|
| 101 |
+
| `weights/mars_spectral.pth` | Mars spectral EVPL, epoch 1000 | spectral model |
|
| 102 |
+
|
| 103 |
+
Segmentation checkpoints are dictionaries with `backbone`, `head`, and `evpl`. Detection and counting checkpoints are a single `state_dict`. `mars_spectral.pth` is the Mars `EVPL` `state_dict`.
|
| 104 |
+
|
| 105 |
+
```python
|
| 106 |
+
import torch
|
| 107 |
+
ckpt = torch.load("weights/modid_twins_svt_small_free.pth", map_location="cpu")
|
| 108 |
+
backbone.load_state_dict(ckpt["backbone"])
|
| 109 |
+
head.load_state_dict(ckpt["head"])
|
| 110 |
+
evpl.load_state_dict(ckpt["evpl"])
|
| 111 |
+
```
|
| 112 |
+
|
| 113 |
+
The weight files sit next to this code under `weights/` in the release folder. Git ignores `*.pth` because the largest file is above GitHub's file size limit. Download the same files from [lyj-flower/PaleVision](https://huggingface.co/lyj-flower/PaleVision).
|
| 114 |
+
|
| 115 |
+
## Notes
|
| 116 |
+
|
| 117 |
+
- Checkpoints written under `work_dir/` during training are ignored by git.
|
| 118 |
+
|
| 119 |
+
## Citation
|
| 120 |
+
|
| 121 |
+
If you use PaleVision in your research, please cite our NeurIPS 2026 paper:
|
| 122 |
+
|
| 123 |
+
```bibtex
|
| 124 |
+
@inproceedings{lu2026paleoinspired,
|
| 125 |
+
title = {Paleoinspired Vision: From Exploring Colour Vision Evolution to Inspiring Camera Design},
|
| 126 |
+
author = {Lu, Yijie and Zong, Zhimin and Zhang, Junjie and Su, Shenghan and Zhao, Zeyun and Cui, Ziteng and Pu, Yan and Lu, Jing and Kojima, Daisuke and Gu, Lin and Fang, Ruogu},
|
| 127 |
+
booktitle = {Advances in Neural Information Processing Systems},
|
| 128 |
+
year = {2026},
|
| 129 |
+
url = {https://luyijie-research.github.io/PaleVision/}
|
| 130 |
+
}
|
| 131 |
+
```
|
configs/lib_hsi_v2.yaml
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
exp:
|
| 2 |
+
backbone: mit_b1
|
| 3 |
+
|
| 4 |
+
dataset:
|
| 5 |
+
root_dir: datasets/LIB-HSI
|
| 6 |
+
num_classes: 44
|
| 7 |
+
input_shape: [256, 256]
|
| 8 |
+
channels: 129
|
| 9 |
+
|
| 10 |
+
train:
|
| 11 |
+
split: train
|
| 12 |
+
samples_per_gpu: 16
|
| 13 |
+
num_epoch: 300
|
| 14 |
+
eval_epoch: 2
|
| 15 |
+
num_workers: 4
|
| 16 |
+
|
| 17 |
+
val:
|
| 18 |
+
split: test
|
| 19 |
+
batch_size: 16
|
| 20 |
+
|
| 21 |
+
optimizer:
|
| 22 |
+
backbone:
|
| 23 |
+
type: AdamW
|
| 24 |
+
learning_rate: 6e-5
|
| 25 |
+
weight_decay: 0.01
|
| 26 |
+
head:
|
| 27 |
+
type: AdamW
|
| 28 |
+
learning_rate: 5e-4
|
| 29 |
+
weight_decay: 0.01
|
| 30 |
+
evpl:
|
| 31 |
+
type: Adam
|
| 32 |
+
learning_rate: 2e-3
|
| 33 |
+
|
| 34 |
+
scheduler:
|
| 35 |
+
type: WarmupCosine
|
| 36 |
+
warmup_epochs: 10
|
| 37 |
+
|
| 38 |
+
loss:
|
| 39 |
+
type: focal
|
| 40 |
+
focal_gamma: 2.0
|
| 41 |
+
use_class_weight: true
|
| 42 |
+
|
| 43 |
+
evpl:
|
| 44 |
+
use_isp: true
|
| 45 |
+
lambda_init_nm: [450.0, 530.0, 580.0]
|
| 46 |
+
freeze: false
|
| 47 |
+
|
| 48 |
+
augmentation:
|
| 49 |
+
use_mixup: false
|
| 50 |
+
mixup_alpha: 0.2
|
| 51 |
+
|
| 52 |
+
training:
|
| 53 |
+
grad_clip: 5.0
|
configs/mars.yaml
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
exp:
|
| 2 |
+
backbone: mit_b0
|
| 3 |
+
|
| 4 |
+
dataset:
|
| 5 |
+
root_dir: datasets
|
| 6 |
+
num_classes: 9
|
| 7 |
+
|
| 8 |
+
train:
|
| 9 |
+
split: train_aug
|
| 10 |
+
samples_per_gpu: 96
|
| 11 |
+
num_epoch: 300
|
| 12 |
+
eval_epoch: 1
|
| 13 |
+
|
| 14 |
+
val:
|
| 15 |
+
split: val
|
| 16 |
+
|
| 17 |
+
optimizer:
|
| 18 |
+
type: SGD
|
| 19 |
+
learning_rate: 0.01
|
| 20 |
+
betas: [0.9, 0.999]
|
| 21 |
+
weight_decay: 5e-4
|
| 22 |
+
|
| 23 |
+
scheduler:
|
| 24 |
+
warmup_iter: 1500
|
| 25 |
+
warmup_ratio: 1e-6
|
| 26 |
+
power: 1.0
|
configs/mhsi.yaml
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
exp:
|
| 2 |
+
backbone: mit_b0
|
| 3 |
+
|
| 4 |
+
dataset:
|
| 5 |
+
root_dir: datasets
|
| 6 |
+
num_classes: 19
|
| 7 |
+
|
| 8 |
+
train:
|
| 9 |
+
split: train_aug
|
| 10 |
+
samples_per_gpu: 96
|
| 11 |
+
num_epoch: 500
|
| 12 |
+
eval_epoch: 1
|
| 13 |
+
|
| 14 |
+
val:
|
| 15 |
+
split: val
|
| 16 |
+
|
| 17 |
+
optimizer:
|
| 18 |
+
type: SGD
|
| 19 |
+
learning_rate: 0.01
|
| 20 |
+
betas: [0.9, 0.999]
|
| 21 |
+
weight_decay: 5e-4
|
| 22 |
+
|
| 23 |
+
scheduler:
|
| 24 |
+
warmup_iter: 1500
|
| 25 |
+
warmup_ratio: 1e-6
|
| 26 |
+
power: 1.0
|
configs/minneapple.yaml
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
exp:
|
| 2 |
+
backbone: mit_b0
|
| 3 |
+
|
| 4 |
+
dataset:
|
| 5 |
+
root_dir: datasets/Fruit
|
| 6 |
+
num_classes: 2
|
| 7 |
+
input_shape: [512, 512]
|
| 8 |
+
channels: 31
|
| 9 |
+
|
| 10 |
+
train:
|
| 11 |
+
split: train
|
| 12 |
+
samples_per_gpu: 2
|
| 13 |
+
num_epoch: 15
|
| 14 |
+
eval_epoch: 5
|
| 15 |
+
num_workers: 2
|
| 16 |
+
|
| 17 |
+
val:
|
| 18 |
+
split: test
|
| 19 |
+
batch_size: 2
|
| 20 |
+
|
| 21 |
+
optimizer:
|
| 22 |
+
type: Adam
|
| 23 |
+
learning_rate: 6e-5
|
| 24 |
+
betas: [0.9, 0.999]
|
| 25 |
+
weight_decay: 5e-4
|
| 26 |
+
|
| 27 |
+
head_optimizer:
|
| 28 |
+
type: SGD
|
| 29 |
+
learning_rate: 5e-4
|
| 30 |
+
momentum: 0.9
|
| 31 |
+
weight_decay: 5e-4
|
| 32 |
+
|
| 33 |
+
evpl_optimizer:
|
| 34 |
+
type: Adam
|
| 35 |
+
learning_rate: 1e-3
|
| 36 |
+
|
| 37 |
+
scheduler:
|
| 38 |
+
type: CosineAnnealing
|
| 39 |
+
warmup_iter: 500
|
| 40 |
+
warmup_ratio: 1e-6
|
| 41 |
+
power: 1.0
|
| 42 |
+
|
| 43 |
+
evpl:
|
| 44 |
+
use_isp: true
|
configs/modid.yaml
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
exp:
|
| 2 |
+
backbone: mit_b0
|
| 3 |
+
|
| 4 |
+
dataset:
|
| 5 |
+
root_dir: datasets
|
| 6 |
+
num_classes: 10
|
| 7 |
+
|
| 8 |
+
train:
|
| 9 |
+
split: train_aug
|
| 10 |
+
samples_per_gpu: 96
|
| 11 |
+
num_epoch: 500
|
| 12 |
+
eval_epoch: 1
|
| 13 |
+
|
| 14 |
+
val:
|
| 15 |
+
split: val
|
| 16 |
+
|
| 17 |
+
optimizer:
|
| 18 |
+
type: SGD
|
| 19 |
+
learning_rate: 0.01
|
| 20 |
+
betas: [0.9, 0.999]
|
| 21 |
+
weight_decay: 5e-4
|
| 22 |
+
|
| 23 |
+
scheduler:
|
| 24 |
+
warmup_iter: 1500
|
| 25 |
+
warmup_ratio: 1e-6
|
| 26 |
+
power: 1.0
|
dataloader/Data_Generate.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from torch.utils.data.dataset import Dataset
|
| 2 |
+
import numpy as np
|
| 3 |
+
import cv2
|
| 4 |
+
import os
|
| 5 |
+
from einops import rearrange, repeat, reduce
|
| 6 |
+
from spectral import *
|
| 7 |
+
from spectral import open_image
|
| 8 |
+
import random
|
| 9 |
+
import math
|
| 10 |
+
from sklearn.metrics import normalized_mutual_info_score
|
| 11 |
+
import warnings
|
| 12 |
+
warnings.filterwarnings('ignore')
|
| 13 |
+
|
| 14 |
+
def cutting_img_mask(img, mask, cutting=224):
|
| 15 |
+
while 1:
|
| 16 |
+
xx = random.randint(0, img.shape[0] - cutting)
|
| 17 |
+
yy = random.randint(0, img.shape[1] - cutting)
|
| 18 |
+
patch_img = img[xx:xx + cutting, yy:yy + cutting]
|
| 19 |
+
patch_mask = mask[xx:xx + cutting, yy:yy + cutting]
|
| 20 |
+
if patch_mask.sum() != 0:
|
| 21 |
+
break
|
| 22 |
+
img = patch_img
|
| 23 |
+
mask = patch_mask
|
| 24 |
+
return (img, mask)
|
| 25 |
+
|
| 26 |
+
def crop_spectral(img, spectral_channel=32):
|
| 27 |
+
orign_channel = img.shape[-1]
|
| 28 |
+
if orign_channel <= spectral_channel:
|
| 29 |
+
return img
|
| 30 |
+
else:
|
| 31 |
+
start_idx = np.random.choice(np.arange(orign_channel - 32))
|
| 32 |
+
img = img[:, :, start_idx:start_idx + spectral_channel]
|
| 33 |
+
return img
|
| 34 |
+
|
| 35 |
+
class Data_Generate_Bile(Dataset):
|
| 36 |
+
|
| 37 |
+
def __init__(self, img_paths, seg_paths, transform=None, channels=None, principal_bands_num=-1, cutting=-1, hyperhsi=False, cropspectral=-1):
|
| 38 |
+
self.img_paths = img_paths
|
| 39 |
+
self.seg_paths = seg_paths
|
| 40 |
+
self.hyperhsi = hyperhsi
|
| 41 |
+
self.transform = transform
|
| 42 |
+
self.channels = channels
|
| 43 |
+
self.principal_bands_num = principal_bands_num
|
| 44 |
+
self.cutting = cutting
|
| 45 |
+
self.cropspectral = cropspectral
|
| 46 |
+
|
| 47 |
+
def __getitem__(self, index):
|
| 48 |
+
img_path = self.img_paths[index]
|
| 49 |
+
img = envi.open(img_path)[:, :, :]
|
| 50 |
+
mask_path = self.seg_paths[index]
|
| 51 |
+
mask = (cv2.imread(mask_path, 0) / 255).astype(np.uint8)
|
| 52 |
+
if img.shape[:2] != mask.shape[:2]:
|
| 53 |
+
mask = cv2.resize(mask, (img.shape[1], img.shape[0]))
|
| 54 |
+
if self.transform != None:
|
| 55 |
+
(img, mask) = self.transform((img, mask))
|
| 56 |
+
if self.cutting > 0:
|
| 57 |
+
(img, mask) = cutting_img_mask(img, mask, self.cutting)
|
| 58 |
+
mask = mask.astype(np.uint8)
|
| 59 |
+
img = img[:, :, self.channels] if self.channels is not None else img
|
| 60 |
+
if self.cropspectral > 0:
|
| 61 |
+
img = crop_spectral(img, self.cropspectral)
|
| 62 |
+
if self.hyperhsi:
|
| 63 |
+
pc = principal_components(img)
|
| 64 |
+
pc_0999 = pc.reduce(fraction=0.999)
|
| 65 |
+
img_pc = pc_0999.transform(img)
|
| 66 |
+
img_pca = img_pc[:, :, 0]
|
| 67 |
+
Ws = dict()
|
| 68 |
+
for i in range(img.shape[-1]):
|
| 69 |
+
Ws[i] = normalized_mutual_info_score(img_pca.reshape(-1), img[:, :, i].reshape(-1))
|
| 70 |
+
indexs = sorted(Ws.items(), key=lambda x: x[1], reverse=True)
|
| 71 |
+
channels = [indexs[i][0] for i in range(16)]
|
| 72 |
+
img = img[:, :, channels]
|
| 73 |
+
if self.principal_bands_num < img.shape[-1] and self.principal_bands_num > 0:
|
| 74 |
+
pc = principal_components(img)
|
| 75 |
+
pc_0999 = pc.reduce(fraction=0.999)
|
| 76 |
+
img_pc = pc_0999.transform(img)
|
| 77 |
+
img = img_pc[:, :, :self.principal_bands_num]
|
| 78 |
+
img = np.transpose(img, (2, 0, 1))
|
| 79 |
+
else:
|
| 80 |
+
img = np.transpose(img, (2, 0, 1))
|
| 81 |
+
img = img.astype(np.float32)
|
| 82 |
+
mask = mask.astype(np.float32)
|
| 83 |
+
return (img, mask[None])
|
| 84 |
+
|
| 85 |
+
def __len__(self):
|
| 86 |
+
return len(self.img_paths)
|
dataloader/Mars.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import numpy as np
|
| 3 |
+
import torch
|
| 4 |
+
import random
|
| 5 |
+
import json
|
| 6 |
+
import h5py
|
| 7 |
+
import cv2
|
| 8 |
+
from PIL import Image
|
| 9 |
+
from torchvision import transforms
|
| 10 |
+
json_data = '{\n "items": [\n {"name": "background", "color_hex_code": "#c00000", "class_group": 0},\n {"name": "Martian Soil", "color_hex_code": "#800000", "class_group": 1},\n {"name": "Sands", "color_hex_code": "#008000", "class_group": 2},\n {"name": "Gravel", "color_hex_code": "#808000", "class_group": 3},\n {"name": "Bedrock", "color_hex_code": "#000080", "class_group": 4},\n {"name": "Rocks", "color_hex_code": "#800080", "class_group": 5},\n {"name": "Tracks", "color_hex_code": "#008080", "class_group": 6},\n {"name": "Shadows", "color_hex_code": "#808080", "class_group": 7},\n {"name": "unknown", "color_hex_code": "#400000", "class_group": 8}\n ]\n}'
|
| 11 |
+
data = json.loads(json_data)
|
| 12 |
+
color_to_class = {}
|
| 13 |
+
for item in data['items']:
|
| 14 |
+
hex_color = item['color_hex_code']
|
| 15 |
+
rgb_color = tuple((int(hex_color[i:i + 2], 16) for i in (1, 3, 5)))
|
| 16 |
+
color_to_class[rgb_color] = item['name']
|
| 17 |
+
color_to_label = {}
|
| 18 |
+
for (idx, item) in enumerate(data['items']):
|
| 19 |
+
hex_color = item['color_hex_code']
|
| 20 |
+
rgb_color = tuple((int(hex_color[i:i + 2], 16) for i in (1, 3, 5)))
|
| 21 |
+
color_to_label[rgb_color] = item['class_group']
|
| 22 |
+
|
| 23 |
+
class MarsDataset(object):
|
| 24 |
+
|
| 25 |
+
def __init__(self, root_dir, input_shape, train):
|
| 26 |
+
self.root_dir = root_dir
|
| 27 |
+
self.input_shape = input_shape
|
| 28 |
+
self.train = train
|
| 29 |
+
img_dir = os.path.join(root_dir, 'img')
|
| 30 |
+
hsi_dir = os.path.join(root_dir, 'hsi')
|
| 31 |
+
label_dir = os.path.join(root_dir, 'label')
|
| 32 |
+
|
| 33 |
+
def _list_valid_files(folder):
|
| 34 |
+
return sorted([f for f in os.listdir(folder) if not f.startswith('.') and os.path.isfile(os.path.join(folder, f))])
|
| 35 |
+
img_files = _list_valid_files(img_dir)
|
| 36 |
+
hsi_files = _list_valid_files(hsi_dir)
|
| 37 |
+
label_files = _list_valid_files(label_dir)
|
| 38 |
+
img_map = {os.path.splitext(f)[0]: f for f in img_files}
|
| 39 |
+
hsi_map = {os.path.splitext(f)[0]: f for f in hsi_files}
|
| 40 |
+
label_map = {os.path.splitext(f)[0]: f for f in label_files}
|
| 41 |
+
common_stems = sorted(set(img_map.keys()) & set(hsi_map.keys()) & set(label_map.keys()))
|
| 42 |
+
if len(common_stems) == 0:
|
| 43 |
+
raise RuntimeError(f'No aligned samples found under {root_dir}. Please check file names in img/hsi/label.')
|
| 44 |
+
self.imgs = [img_map[s] for s in common_stems]
|
| 45 |
+
self.hsi = [hsi_map[s] for s in common_stems]
|
| 46 |
+
self.label = [label_map[s] for s in common_stems]
|
| 47 |
+
|
| 48 |
+
def __getitem__(self, idx):
|
| 49 |
+
rgb_mean = (0.0, 0.0, 0.0)
|
| 50 |
+
rgb_std = (255.0, 255.0, 255.0)
|
| 51 |
+
(h, w) = self.input_shape
|
| 52 |
+
img_path = os.path.join(self.root_dir, 'img', self.imgs[idx])
|
| 53 |
+
hsi_path = os.path.join(self.root_dir, 'hsi', self.hsi[idx])
|
| 54 |
+
label_path = os.path.join(self.root_dir, 'label', self.label[idx])
|
| 55 |
+
if self.train:
|
| 56 |
+
with h5py.File(hsi_path, 'r') as mat_data:
|
| 57 |
+
cube = np.array(mat_data['cube'])
|
| 58 |
+
intensity = 1
|
| 59 |
+
lam31 = np.array([400, 410, 420, 430, 440, 450, 460, 470, 480, 490, 500, 510, 520, 530, 540, 550, 560, 570, 580, 590, 600, 610, 620, 630, 640, 650, 660, 670, 680, 690, 700])
|
| 60 |
+
hsi_one_channel_list = []
|
| 61 |
+
resized_data = np.empty((31, h, w), dtype=np.float32)
|
| 62 |
+
for i in range(cube.shape[0]):
|
| 63 |
+
img_nb = i
|
| 64 |
+
img_slice = cube[img_nb, :, :]
|
| 65 |
+
img_adjusted = img_slice * intensity
|
| 66 |
+
img_adjusted = np.clip(img_adjusted, 0, 1)
|
| 67 |
+
img_adjusted = np.transpose(img_adjusted, (1, 0))
|
| 68 |
+
img_uint8 = (img_adjusted * 255).astype(np.uint8)
|
| 69 |
+
band_img = Image.fromarray(img_uint8)
|
| 70 |
+
hsi_one_channel_list.append(band_img)
|
| 71 |
+
rgb = Image.open(img_path).convert('RGB')
|
| 72 |
+
label_image = cv2.imread(label_path)
|
| 73 |
+
label_image = cv2.cvtColor(label_image, cv2.COLOR_BGR2RGB)
|
| 74 |
+
(height, width, _) = label_image.shape
|
| 75 |
+
label = np.zeros((height, width), dtype=np.uint8)
|
| 76 |
+
for (rgb_color, labels) in color_to_label.items():
|
| 77 |
+
mask = np.all(label_image == np.array(rgb_color), axis=-1)
|
| 78 |
+
label[mask] = labels
|
| 79 |
+
label_pil = Image.fromarray(label)
|
| 80 |
+
(hsi_one_channel_list, rgb, label_pil) = self.random_flip_LR(hsi_one_channel_list, rgb, label_pil)
|
| 81 |
+
(hsi_one_channel_list, rgb, label_pil) = self.random_flip_UD(hsi_one_channel_list, rgb, label_pil)
|
| 82 |
+
(hsi_one_channel_list, rgb, label_pil) = self.Random_Crop(hsi_one_channel_list, rgb, label_pil)
|
| 83 |
+
for index in range(len(hsi_one_channel_list)):
|
| 84 |
+
hsi_one_channel_list[index] = hsi_one_channel_list[index].resize((w, h), Image.BILINEAR)
|
| 85 |
+
rgb = rgb.resize((w, h), Image.BILINEAR)
|
| 86 |
+
label_pil = label_pil.resize((w, h), Image.NEAREST)
|
| 87 |
+
for i in range(31):
|
| 88 |
+
resized_data[i, :, :] = np.array(hsi_one_channel_list[i], dtype=np.float32)
|
| 89 |
+
hsi = resized_data
|
| 90 |
+
rgb = np.array(rgb, dtype=np.float32)
|
| 91 |
+
label = np.array(label_pil, dtype=np.uint8)
|
| 92 |
+
label[label >= 9] = 255
|
| 93 |
+
label = torch.tensor(label, dtype=torch.uint8)
|
| 94 |
+
mask = torch.where(label == 7, torch.tensor(1), torch.tensor(0))
|
| 95 |
+
transform_rgb = transforms.Compose([transforms.ToTensor(), transforms.Normalize(rgb_mean, rgb_std)])
|
| 96 |
+
rgb = transform_rgb(rgb)
|
| 97 |
+
return (hsi, rgb, label, mask)
|
| 98 |
+
else:
|
| 99 |
+
img_path = os.path.join(self.root_dir, 'img', self.imgs[idx])
|
| 100 |
+
hsi_path = os.path.join(self.root_dir, 'hsi', self.hsi[idx])
|
| 101 |
+
label_path = os.path.join(self.root_dir, 'label', self.label[idx])
|
| 102 |
+
with h5py.File(hsi_path, 'r') as mat_data:
|
| 103 |
+
cube = np.array(mat_data['cube'])
|
| 104 |
+
intensity = 1
|
| 105 |
+
lam31 = np.array([400, 410, 420, 430, 440, 450, 460, 470, 480, 490, 500, 510, 520, 530, 540, 550, 560, 570, 580, 590, 600, 610, 620, 630, 640, 650, 660, 670, 680, 690, 700])
|
| 106 |
+
hsi_one_channel_list = []
|
| 107 |
+
resized_data = np.empty((31, h, w), dtype=np.float32)
|
| 108 |
+
for i in range(cube.shape[0]):
|
| 109 |
+
img_nb = i
|
| 110 |
+
img_slice = cube[img_nb, :, :]
|
| 111 |
+
img_adjusted = img_slice * intensity
|
| 112 |
+
img_adjusted = np.clip(img_adjusted, 0, 1)
|
| 113 |
+
img_adjusted = np.transpose(img_adjusted, (1, 0))
|
| 114 |
+
img_uint8 = (img_adjusted * 255).astype(np.uint8)
|
| 115 |
+
band_img = Image.fromarray(img_uint8)
|
| 116 |
+
hsi_one_channel_list.append(band_img)
|
| 117 |
+
rgb = Image.open(img_path).convert('RGB')
|
| 118 |
+
label_image = cv2.imread(label_path)
|
| 119 |
+
label_image = cv2.cvtColor(label_image, cv2.COLOR_BGR2RGB)
|
| 120 |
+
(height, width, _) = label_image.shape
|
| 121 |
+
label = np.zeros((height, width), dtype=np.uint8)
|
| 122 |
+
for (rgb_color, labels) in color_to_label.items():
|
| 123 |
+
mask = np.all(label_image == np.array(rgb_color), axis=-1)
|
| 124 |
+
label[mask] = labels
|
| 125 |
+
label_pil = Image.fromarray(label)
|
| 126 |
+
for index in range(len(hsi_one_channel_list)):
|
| 127 |
+
hsi_one_channel_list[index] = hsi_one_channel_list[index].resize((w, h), Image.BILINEAR)
|
| 128 |
+
rgb = rgb.resize((w, h), Image.BILINEAR)
|
| 129 |
+
label_pil = label_pil.resize((w, h), Image.NEAREST)
|
| 130 |
+
for i in range(31):
|
| 131 |
+
resized_data[i, :, :] = np.array(hsi_one_channel_list[i], dtype=np.float32)
|
| 132 |
+
hsi = resized_data
|
| 133 |
+
rgb = np.array(rgb, dtype=np.float32)
|
| 134 |
+
label = np.array(label_pil, dtype=np.uint8)
|
| 135 |
+
label[label >= 9] = 255
|
| 136 |
+
label = torch.tensor(label, dtype=torch.uint8)
|
| 137 |
+
mask = torch.where(label == 7, torch.tensor(1), torch.tensor(0))
|
| 138 |
+
transform_rgb = transforms.Compose([transforms.ToTensor(), transforms.Normalize(rgb_mean, rgb_std)])
|
| 139 |
+
rgb = transform_rgb(rgb)
|
| 140 |
+
return (hsi, rgb, label, mask)
|
| 141 |
+
|
| 142 |
+
def __len__(self):
|
| 143 |
+
return len(self.imgs)
|
| 144 |
+
|
| 145 |
+
def random_flip_LR(self, hsi_one_channel_list, rgb, label):
|
| 146 |
+
if random.random() > 0.5:
|
| 147 |
+
for index in range(len(hsi_one_channel_list)):
|
| 148 |
+
hsi_one_channel_list[index] = hsi_one_channel_list[index].transpose(Image.FLIP_LEFT_RIGHT)
|
| 149 |
+
rgb = rgb.transpose(Image.FLIP_LEFT_RIGHT)
|
| 150 |
+
label = label.transpose(Image.FLIP_LEFT_RIGHT)
|
| 151 |
+
return (hsi_one_channel_list, rgb, label)
|
| 152 |
+
|
| 153 |
+
def random_flip_UD(self, hsi_one_channel_list, rgb, label):
|
| 154 |
+
if random.random() > 0.5:
|
| 155 |
+
for index in range(len(hsi_one_channel_list)):
|
| 156 |
+
hsi_one_channel_list[index] = hsi_one_channel_list[index].transpose(Image.FLIP_TOP_BOTTOM)
|
| 157 |
+
rgb = rgb.transpose(Image.FLIP_TOP_BOTTOM)
|
| 158 |
+
label = label.transpose(Image.FLIP_TOP_BOTTOM)
|
| 159 |
+
return (hsi_one_channel_list, rgb, label)
|
| 160 |
+
|
| 161 |
+
def get_params(self, low):
|
| 162 |
+
(self.h, self.w) = low.size
|
| 163 |
+
self.crop_height = min(128, self.h)
|
| 164 |
+
self.crop_width = min(128, self.w)
|
| 165 |
+
i = random.randint(0, max(self.h - self.crop_height, 0))
|
| 166 |
+
j = random.randint(0, max(self.w - self.crop_width, 0))
|
| 167 |
+
return (i, j)
|
| 168 |
+
|
| 169 |
+
def Random_Crop(self, hsi_one_channel_list, rgb, label):
|
| 170 |
+
(self.i, self.j) = self.get_params(rgb)
|
| 171 |
+
if random.random() > 0.5:
|
| 172 |
+
rgb = rgb.crop((self.j, self.i, self.j + self.crop_width, self.i + self.crop_height))
|
| 173 |
+
label = label.crop((self.j, self.i, self.j + self.crop_width, self.i + self.crop_height))
|
| 174 |
+
for index in range(len(hsi_one_channel_list)):
|
| 175 |
+
hsi_one_channel_list[index] = hsi_one_channel_list[index].crop((self.j, self.i, self.j + self.crop_width, self.i + self.crop_height))
|
| 176 |
+
return (hsi_one_channel_list, rgb, label)
|
dataloader/__init__.py
ADDED
|
File without changes
|
dataloader/argument.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import cv2
|
| 2 |
+
import numpy as np
|
| 3 |
+
import skimage.io
|
| 4 |
+
import albumentations as A
|
| 5 |
+
|
| 6 |
+
def resize(image, size=(128, 128)):
|
| 7 |
+
return cv2.resize(image, size)
|
| 8 |
+
|
| 9 |
+
def add_gaussian_noise(x, sigma):
|
| 10 |
+
x += np.random.randn(*x.shape) * sigma
|
| 11 |
+
x = np.clip(x, 0.0, 1.0)
|
| 12 |
+
return x
|
| 13 |
+
|
| 14 |
+
def _evaluate_ratio(ratio):
|
| 15 |
+
if ratio <= 0.0:
|
| 16 |
+
return False
|
| 17 |
+
return np.random.uniform() < ratio
|
| 18 |
+
|
| 19 |
+
def apply_aug(aug, image, mask=None):
|
| 20 |
+
augment = aug(image=image, mask=mask)
|
| 21 |
+
return (augment['image'], augment['mask'])
|
| 22 |
+
|
| 23 |
+
class Transform:
|
| 24 |
+
|
| 25 |
+
def __init__(self, size=None, train=True, BrightContrast_ration=0.0, noise_ratio=0.0, cutout_ratio=0.0, grid_distortion_ratio=0.0, elastic_distortion_ratio=0.0, piece_affine_ratio=0.0, ssr_ratio=0.0, Rotate_ratio=0.0, Flip_ratio=0.0):
|
| 26 |
+
self.size = size
|
| 27 |
+
self.train = train
|
| 28 |
+
self.noise_ratio = noise_ratio
|
| 29 |
+
self.BrightContrast_ration = BrightContrast_ration
|
| 30 |
+
self.cutout_ratio = cutout_ratio
|
| 31 |
+
self.grid_distortion_ratio = grid_distortion_ratio
|
| 32 |
+
self.elastic_distortion_ratio = elastic_distortion_ratio
|
| 33 |
+
self.piece_affine_ratio = piece_affine_ratio
|
| 34 |
+
self.ssr_ratio = ssr_ratio
|
| 35 |
+
self.Rotate_ratio = Rotate_ratio
|
| 36 |
+
self.Flip_ratio = Flip_ratio
|
| 37 |
+
|
| 38 |
+
def __call__(self, example):
|
| 39 |
+
if self.train:
|
| 40 |
+
(x, y) = example
|
| 41 |
+
else:
|
| 42 |
+
x = example
|
| 43 |
+
if self.size is not None:
|
| 44 |
+
x = resize(x, size=self.size)
|
| 45 |
+
if _evaluate_ratio(self.BrightContrast_ration):
|
| 46 |
+
x = apply_aug(A.RandomBrightnessContrast(p=1.0), x)
|
| 47 |
+
if _evaluate_ratio(self.noise_ratio):
|
| 48 |
+
r = np.random.uniform()
|
| 49 |
+
if r < 0.5:
|
| 50 |
+
x = apply_aug(A.GaussNoise(var_limit=5.0 / 255.0, p=1.0), x)
|
| 51 |
+
else:
|
| 52 |
+
x = apply_aug(A.MultiplicativeNoise(p=1.0), x)
|
| 53 |
+
if _evaluate_ratio(self.grid_distortion_ratio):
|
| 54 |
+
(x, y) = apply_aug(A.GridDistortion(p=1.0), x, y)
|
| 55 |
+
if _evaluate_ratio(self.elastic_distortion_ratio):
|
| 56 |
+
(x, y) = apply_aug(A.ElasticTransform(sigma=50, alpha=1, p=1.0), x, y)
|
| 57 |
+
if _evaluate_ratio(self.Rotate_ratio):
|
| 58 |
+
(x, y) = apply_aug(A.Rotate(p=1.0), x, y)
|
| 59 |
+
if _evaluate_ratio(self.Flip_ratio):
|
| 60 |
+
(x, y) = apply_aug(A.Flip(p=1.0), x, y)
|
| 61 |
+
if self.train:
|
| 62 |
+
return (x, y)
|
| 63 |
+
else:
|
| 64 |
+
return x
|
dataloader/lib_hsi.py
ADDED
|
@@ -0,0 +1,322 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import numpy as np
|
| 3 |
+
import torch
|
| 4 |
+
import random
|
| 5 |
+
import cv2
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from PIL import Image
|
| 8 |
+
from torch.utils.data.dataset import Dataset
|
| 9 |
+
import h5py
|
| 10 |
+
import scipy.io
|
| 11 |
+
|
| 12 |
+
class LIBHSIDataset(Dataset):
|
| 13 |
+
RGB_LABEL_COLORS = [(0, 122, 16), (2, 195, 145), (4, 108, 16), (12, 229, 68), (13, 186, 180), (32, 49, 228), (33, 98, 194), (34, 31, 153), (37, 78, 32), (65, 170, 96), (67, 145, 3), (69, 174, 186), (80, 84, 195), (82, 185, 203), (98, 250, 227), (108, 152, 134), (113, 134, 124), (128, 169, 150), (139, 150, 228), (144, 142, 142), (160, 187, 213), (167, 174, 171), (172, 228, 99), (181, 42, 181), (184, 117, 40), (187, 5, 74), (188, 114, 203), (189, 196, 26), (195, 127, 115), (199, 197, 189), (201, 141, 150), (210, 184, 98), (212, 78, 78), (212, 204, 228), (216, 182, 111), (222, 222, 222), (232, 183, 100), (236, 233, 124), (237, 128, 22), (240, 212, 173), (253, 149, 138), (255, 0, 128), (255, 128, 64), (255, 128, 192)]
|
| 14 |
+
PALETTE = RGB_LABEL_COLORS
|
| 15 |
+
|
| 16 |
+
def __init__(self, root_dir, input_shape, train=True, num_classes=44, target_bands=31, spectral_range=(300, 700)):
|
| 17 |
+
self.root_dir = root_dir
|
| 18 |
+
self.input_shape = input_shape
|
| 19 |
+
self.train = train
|
| 20 |
+
self.num_classes = num_classes
|
| 21 |
+
self.original_channels = 204
|
| 22 |
+
self.target_bands = target_bands
|
| 23 |
+
self.spectral_range = spectral_range
|
| 24 |
+
self.ignore_index = 255
|
| 25 |
+
self._label_warning_printed = False
|
| 26 |
+
self._label_mapping_warning_printed = False
|
| 27 |
+
self._palette_rgb = np.array(self.RGB_LABEL_COLORS, dtype=np.int16)
|
| 28 |
+
self.max_color_distance = 8.0
|
| 29 |
+
self.original_wavelengths = np.linspace(397, 1003, 204)
|
| 30 |
+
if target_bands is not None:
|
| 31 |
+
self.channels = target_bands
|
| 32 |
+
start_idx = np.argmin(np.abs(self.original_wavelengths - spectral_range[0]))
|
| 33 |
+
end_idx = np.argmin(np.abs(self.original_wavelengths - spectral_range[1]))
|
| 34 |
+
self.spectral_start_idx = start_idx
|
| 35 |
+
self.spectral_end_idx = end_idx
|
| 36 |
+
self.bands_in_range = end_idx - start_idx + 1
|
| 37 |
+
self.wavelengths = np.linspace(spectral_range[0], spectral_range[1], target_bands)
|
| 38 |
+
print(f'[LIBHSIDataset] Downsampling: {self.original_channels} -> {target_bands} bands')
|
| 39 |
+
print(f' Spectral range: {spectral_range[0]}-{spectral_range[1]}nm')
|
| 40 |
+
print(f' Original indices: {start_idx} to {end_idx} ({self.bands_in_range} bands)')
|
| 41 |
+
else:
|
| 42 |
+
self.channels = 204
|
| 43 |
+
self.wavelengths = self.original_wavelengths
|
| 44 |
+
if self.train:
|
| 45 |
+
self.hsi_dir = os.path.join(root_dir, 'train/hsi')
|
| 46 |
+
self.label_dir = os.path.join(root_dir, 'train/labels')
|
| 47 |
+
else:
|
| 48 |
+
self.hsi_dir = os.path.join(root_dir, 'test/hsi')
|
| 49 |
+
self.label_dir = os.path.join(root_dir, 'test/labels')
|
| 50 |
+
self.hsi_files = self._collect_hdr_files(self.hsi_dir)
|
| 51 |
+
self.label_files = self._match_files_by_stem(self.hsi_files, self.label_dir, 'label')
|
| 52 |
+
self.rgb_to_class = self._build_rgb_label_mapping()
|
| 53 |
+
|
| 54 |
+
def _build_rgb_label_mapping(self):
|
| 55 |
+
rgb_to_class = {}
|
| 56 |
+
for (class_id, rgb) in enumerate(self.RGB_LABEL_COLORS):
|
| 57 |
+
rgb_to_class[rgb] = class_id
|
| 58 |
+
return rgb_to_class
|
| 59 |
+
|
| 60 |
+
def _collect_hdr_files(self, folder_path):
|
| 61 |
+
hdr_files = []
|
| 62 |
+
for file_name in sorted(os.listdir(folder_path)):
|
| 63 |
+
file_path = os.path.join(folder_path, file_name)
|
| 64 |
+
if not os.path.isfile(file_path):
|
| 65 |
+
continue
|
| 66 |
+
if file_name.lower().endswith('.hdr'):
|
| 67 |
+
hdr_files.append(file_name)
|
| 68 |
+
if len(hdr_files) == 0:
|
| 69 |
+
raise RuntimeError(f'No .hdr files found in {folder_path}')
|
| 70 |
+
return hdr_files
|
| 71 |
+
|
| 72 |
+
def _match_files_by_stem(self, hsi_files, target_dir, target_name):
|
| 73 |
+
target_map = {}
|
| 74 |
+
for file_name in sorted(os.listdir(target_dir)):
|
| 75 |
+
file_path = os.path.join(target_dir, file_name)
|
| 76 |
+
if not os.path.isfile(file_path):
|
| 77 |
+
continue
|
| 78 |
+
stem = os.path.splitext(file_name)[0]
|
| 79 |
+
target_map[stem] = file_name
|
| 80 |
+
matched_files = []
|
| 81 |
+
missing_stems = []
|
| 82 |
+
for hsi_file in hsi_files:
|
| 83 |
+
stem = os.path.splitext(hsi_file)[0]
|
| 84 |
+
if stem not in target_map:
|
| 85 |
+
missing_stems.append(stem)
|
| 86 |
+
else:
|
| 87 |
+
matched_files.append(target_map[stem])
|
| 88 |
+
if len(missing_stems) > 0:
|
| 89 |
+
preview = ', '.join(missing_stems[:5])
|
| 90 |
+
raise RuntimeError(f'Missing {target_name} files for {len(missing_stems)} HSI samples in {target_dir}. Examples: {preview}')
|
| 91 |
+
return matched_files
|
| 92 |
+
|
| 93 |
+
def __len__(self):
|
| 94 |
+
return len(self.hsi_files)
|
| 95 |
+
|
| 96 |
+
def __getitem__(self, idx):
|
| 97 |
+
(h, w) = self.input_shape
|
| 98 |
+
hsi_path = os.path.join(self.hsi_dir, self.hsi_files[idx])
|
| 99 |
+
hsi = self._load_hsi(hsi_path)
|
| 100 |
+
print('shit1', hsi.shape)
|
| 101 |
+
label_path = os.path.join(self.label_dir, self.label_files[idx])
|
| 102 |
+
label = self._load_label(label_path)
|
| 103 |
+
if self.train:
|
| 104 |
+
(hsi, label) = self._augment(hsi, label)
|
| 105 |
+
print('shit2', hsi.shape)
|
| 106 |
+
hsi = self._resize_hsi(hsi, (h, w))
|
| 107 |
+
label = self._resize_label(label, (h, w))
|
| 108 |
+
print('shit3', hsi.shape)
|
| 109 |
+
hsi = torch.tensor(hsi, dtype=torch.float32)
|
| 110 |
+
label = torch.tensor(label, dtype=torch.long)
|
| 111 |
+
return (hsi, label)
|
| 112 |
+
|
| 113 |
+
def _load_hsi(self, path):
|
| 114 |
+
ext = os.path.splitext(path)[1].lower()
|
| 115 |
+
if ext == '.npy':
|
| 116 |
+
hsi = np.load(path).astype(np.float32)
|
| 117 |
+
elif ext == '.mat':
|
| 118 |
+
try:
|
| 119 |
+
with h5py.File(path, 'r') as f:
|
| 120 |
+
for key in ['cube', 'hsi', 'data', 'image']:
|
| 121 |
+
if key in f.keys():
|
| 122 |
+
hsi = np.array(f[key], dtype=np.float32)
|
| 123 |
+
break
|
| 124 |
+
except:
|
| 125 |
+
mat = scipy.io.loadmat(path)
|
| 126 |
+
for key in ['cube', 'hsi', 'data', 'image']:
|
| 127 |
+
if key in mat.keys():
|
| 128 |
+
hsi = mat[key].astype(np.float32)
|
| 129 |
+
break
|
| 130 |
+
elif ext == '.hdr':
|
| 131 |
+
import spectral
|
| 132 |
+
hsi_img = spectral.open_image(path)
|
| 133 |
+
hsi = np.array(hsi_img.load(), dtype=np.float32)
|
| 134 |
+
hsi = np.transpose(hsi, (2, 0, 1))
|
| 135 |
+
else:
|
| 136 |
+
raise ValueError(f'Unsupported HSI format: {ext}')
|
| 137 |
+
if len(hsi.shape) == 3 and hsi.shape[-1] == self.original_channels:
|
| 138 |
+
hsi = np.transpose(hsi, (2, 0, 1))
|
| 139 |
+
if self.target_bands is not None:
|
| 140 |
+
hsi = self._downsample_bands(hsi)
|
| 141 |
+
hsi_min = np.percentile(hsi, 1)
|
| 142 |
+
hsi_max = np.percentile(hsi, 99)
|
| 143 |
+
if hsi_max > hsi_min:
|
| 144 |
+
hsi = np.clip(hsi, hsi_min, hsi_max)
|
| 145 |
+
hsi = (hsi - hsi_min) / (hsi_max - hsi_min)
|
| 146 |
+
elif hsi.max() > 0:
|
| 147 |
+
hsi = hsi / hsi.max()
|
| 148 |
+
return hsi
|
| 149 |
+
|
| 150 |
+
def _downsample_bands(self, hsi):
|
| 151 |
+
(C, H, W) = hsi.shape
|
| 152 |
+
hsi_in_range = hsi[self.spectral_start_idx:self.spectral_end_idx + 1, :, :]
|
| 153 |
+
bands_in_range = hsi_in_range.shape[0]
|
| 154 |
+
if self.target_bands >= bands_in_range:
|
| 155 |
+
indices = np.linspace(0, bands_in_range - 1, self.target_bands).astype(int)
|
| 156 |
+
downsampled = hsi_in_range[indices, :, :]
|
| 157 |
+
else:
|
| 158 |
+
downsampled = np.zeros((self.target_bands, H, W), dtype=np.float32)
|
| 159 |
+
step = bands_in_range / self.target_bands
|
| 160 |
+
for i in range(self.target_bands):
|
| 161 |
+
idx_start = int(i * step)
|
| 162 |
+
idx_end = int((i + 1) * step)
|
| 163 |
+
idx_end = min(idx_end, bands_in_range)
|
| 164 |
+
if idx_end > idx_start:
|
| 165 |
+
downsampled[i] = np.mean(hsi_in_range[idx_start:idx_end, :, :], axis=0)
|
| 166 |
+
else:
|
| 167 |
+
downsampled[i] = hsi_in_range[idx_start, :, :]
|
| 168 |
+
return downsampled
|
| 169 |
+
|
| 170 |
+
def _load_label(self, path):
|
| 171 |
+
raw_label = cv2.imread(path, cv2.IMREAD_UNCHANGED)
|
| 172 |
+
if raw_label is None:
|
| 173 |
+
raw_label = np.array(Image.open(path))
|
| 174 |
+
if raw_label.ndim == 2:
|
| 175 |
+
label = raw_label.astype(np.int64)
|
| 176 |
+
invalid_mask = (label < 0) | (label >= self.num_classes)
|
| 177 |
+
if np.any(invalid_mask):
|
| 178 |
+
label[invalid_mask] = self.ignore_index
|
| 179 |
+
return label
|
| 180 |
+
if raw_label.ndim == 3 and raw_label.shape[2] == 4:
|
| 181 |
+
raw_label = raw_label[:, :, :3]
|
| 182 |
+
if raw_label.ndim != 3 or raw_label.shape[2] != 3:
|
| 183 |
+
raise ValueError(f'Unsupported label shape {raw_label.shape} for file: {path}')
|
| 184 |
+
label_rgb = cv2.cvtColor(raw_label, cv2.COLOR_BGR2RGB)
|
| 185 |
+
return self._rgb_to_class_label(label_rgb, path)
|
| 186 |
+
|
| 187 |
+
def _rgb_to_class_label(self, label_rgb, path):
|
| 188 |
+
(h, w) = label_rgb.shape[:2]
|
| 189 |
+
label = np.full((h, w), fill_value=self.ignore_index, dtype=np.int64)
|
| 190 |
+
for (rgb, class_id) in self.rgb_to_class.items():
|
| 191 |
+
mask = (label_rgb[:, :, 0] == rgb[0]) & (label_rgb[:, :, 1] == rgb[1]) & (label_rgb[:, :, 2] == rgb[2])
|
| 192 |
+
label[mask] = class_id
|
| 193 |
+
unmapped_mask = label == self.ignore_index
|
| 194 |
+
if np.any(unmapped_mask):
|
| 195 |
+
(ys, xs) = np.where(unmapped_mask)
|
| 196 |
+
chunk_size = 50000
|
| 197 |
+
for start in range(0, len(ys), chunk_size):
|
| 198 |
+
end = min(start + chunk_size, len(ys))
|
| 199 |
+
y_chunk = ys[start:end]
|
| 200 |
+
x_chunk = xs[start:end]
|
| 201 |
+
rgb_chunk = label_rgb[y_chunk, x_chunk].astype(np.int16)
|
| 202 |
+
dist = np.linalg.norm(rgb_chunk[:, None, :] - self._palette_rgb[None, :, :], axis=2)
|
| 203 |
+
nearest_idx = np.argmin(dist, axis=1)
|
| 204 |
+
nearest_dist = dist[np.arange(len(nearest_idx)), nearest_idx]
|
| 205 |
+
valid_fallback = nearest_dist <= self.max_color_distance
|
| 206 |
+
if np.any(valid_fallback):
|
| 207 |
+
label[y_chunk[valid_fallback], x_chunk[valid_fallback]] = nearest_idx[valid_fallback]
|
| 208 |
+
unmapped_mask = label == self.ignore_index
|
| 209 |
+
if np.any(unmapped_mask) and (not self._label_warning_printed):
|
| 210 |
+
unmapped_rgb = label_rgb[unmapped_mask]
|
| 211 |
+
unique_unmapped = np.unique(unmapped_rgb.reshape(-1, 3), axis=0)[:5]
|
| 212 |
+
unmapped_ratio = float(unmapped_mask.mean())
|
| 213 |
+
print(f'[LIBHSI] Found unmapped RGB in {path}, ignore_ratio={unmapped_ratio:.4f}, examples={unique_unmapped.tolist()}')
|
| 214 |
+
self._label_warning_printed = True
|
| 215 |
+
if not self._label_mapping_warning_printed:
|
| 216 |
+
print(f'[LIBHSI] Applied RGB->class mapping. num_colors={len(self.rgb_to_class)}, target ids range=[0, {self.num_classes - 1}]')
|
| 217 |
+
self._label_mapping_warning_printed = True
|
| 218 |
+
return label
|
| 219 |
+
|
| 220 |
+
def _resize_hsi(self, hsi, target_size):
|
| 221 |
+
(h, w) = target_size
|
| 222 |
+
(c, orig_h, orig_w) = hsi.shape
|
| 223 |
+
if (orig_h, orig_w) == (h, w):
|
| 224 |
+
return hsi
|
| 225 |
+
resized = np.empty((c, h, w), dtype=np.float32)
|
| 226 |
+
for i in range(c):
|
| 227 |
+
resized[i] = cv2.resize(hsi[i], (w, h), interpolation=cv2.INTER_LINEAR)
|
| 228 |
+
return resized
|
| 229 |
+
|
| 230 |
+
def _resize_label(self, label, target_size):
|
| 231 |
+
(h, w) = target_size
|
| 232 |
+
if label.shape == (h, w):
|
| 233 |
+
return label
|
| 234 |
+
return cv2.resize(label, (w, h), interpolation=cv2.INTER_NEAREST)
|
| 235 |
+
|
| 236 |
+
def _augment(self, hsi, label):
|
| 237 |
+
if random.random() > 0.5:
|
| 238 |
+
(c, orig_h, orig_w) = hsi.shape
|
| 239 |
+
scale = random.uniform(0.7, 1.0)
|
| 240 |
+
crop_h = max(64, int(orig_h * scale))
|
| 241 |
+
crop_w = max(64, int(orig_w * scale))
|
| 242 |
+
if crop_h < orig_h and crop_w < orig_w:
|
| 243 |
+
top = random.randint(0, orig_h - crop_h)
|
| 244 |
+
left = random.randint(0, orig_w - crop_w)
|
| 245 |
+
hsi = hsi[:, top:top + crop_h, left:left + crop_w]
|
| 246 |
+
label = label[top:top + crop_h, left:left + crop_w]
|
| 247 |
+
if random.random() > 0.5:
|
| 248 |
+
hsi = np.flip(hsi, axis=2).copy()
|
| 249 |
+
label = np.flip(label, axis=1).copy()
|
| 250 |
+
if random.random() > 0.5:
|
| 251 |
+
hsi = np.flip(hsi, axis=1).copy()
|
| 252 |
+
label = np.flip(label, axis=0).copy()
|
| 253 |
+
k = random.randint(0, 3)
|
| 254 |
+
if k > 0:
|
| 255 |
+
hsi = np.rot90(hsi, k, axes=(1, 2)).copy()
|
| 256 |
+
label = np.rot90(label, k, axes=(0, 1)).copy()
|
| 257 |
+
return (hsi, label)
|
| 258 |
+
|
| 259 |
+
def get_wavelengths(self):
|
| 260 |
+
return self.wavelengths
|
| 261 |
+
|
| 262 |
+
class LIBHSIColorDataset(LIBHSIDataset):
|
| 263 |
+
|
| 264 |
+
def __init__(self, root_dir, input_shape, train=True, num_classes=44):
|
| 265 |
+
super().__init__(root_dir, input_shape, train, num_classes)
|
| 266 |
+
if self.train:
|
| 267 |
+
self.rgb_dir = os.path.join(root_dir, 'train/rgb')
|
| 268 |
+
else:
|
| 269 |
+
self.rgb_dir = os.path.join(root_dir, 'test/rgb')
|
| 270 |
+
if os.path.exists(self.rgb_dir):
|
| 271 |
+
rgb_map = {}
|
| 272 |
+
for file_name in sorted(os.listdir(self.rgb_dir)):
|
| 273 |
+
file_path = os.path.join(self.rgb_dir, file_name)
|
| 274 |
+
if not os.path.isfile(file_path):
|
| 275 |
+
continue
|
| 276 |
+
stem = os.path.splitext(file_name)[0]
|
| 277 |
+
rgb_map[stem] = file_name
|
| 278 |
+
self.rgb_files = []
|
| 279 |
+
for hsi_file in self.hsi_files:
|
| 280 |
+
stem = os.path.splitext(hsi_file)[0]
|
| 281 |
+
self.rgb_files.append(rgb_map.get(stem))
|
| 282 |
+
else:
|
| 283 |
+
self.rgb_files = None
|
| 284 |
+
|
| 285 |
+
def __getitem__(self, idx):
|
| 286 |
+
(h, w) = self.input_shape
|
| 287 |
+
hsi_path = os.path.join(self.hsi_dir, self.hsi_files[idx])
|
| 288 |
+
hsi = self._load_hsi(hsi_path)
|
| 289 |
+
label_path = os.path.join(self.label_dir, self.label_files[idx])
|
| 290 |
+
label = self._load_label(label_path)
|
| 291 |
+
rgb = None
|
| 292 |
+
if self.rgb_files is not None and self.rgb_files[idx] is not None:
|
| 293 |
+
rgb_path = os.path.join(self.rgb_dir, self.rgb_files[idx])
|
| 294 |
+
rgb = cv2.imread(rgb_path)
|
| 295 |
+
if rgb is not None:
|
| 296 |
+
rgb = cv2.cvtColor(rgb, cv2.COLOR_BGR2RGB)
|
| 297 |
+
rgb = cv2.resize(rgb, (w, h))
|
| 298 |
+
rgb = rgb.astype(np.float32) / 255.0
|
| 299 |
+
rgb = np.transpose(rgb, (2, 0, 1))
|
| 300 |
+
if self.train:
|
| 301 |
+
(hsi, label) = self._augment(hsi, label)
|
| 302 |
+
if rgb is not None:
|
| 303 |
+
pass
|
| 304 |
+
hsi = self._resize_hsi(hsi, (h, w))
|
| 305 |
+
label = self._resize_label(label, (h, w))
|
| 306 |
+
hsi = torch.tensor(hsi, dtype=torch.float32)
|
| 307 |
+
label = torch.tensor(label, dtype=torch.long)
|
| 308 |
+
if rgb is not None:
|
| 309 |
+
rgb = torch.tensor(rgb, dtype=torch.float32)
|
| 310 |
+
return (hsi, rgb, label)
|
| 311 |
+
return (hsi, label)
|
| 312 |
+
if __name__ == '__main__':
|
| 313 |
+
root_path = 'datasets/LIB-HSI'
|
| 314 |
+
input_shape = [256, 256]
|
| 315 |
+
train_dataset = LIBHSIDataset(root_dir=root_path, input_shape=input_shape, train=True)
|
| 316 |
+
print(f'Dataset size: {len(train_dataset)}')
|
| 317 |
+
print(f'Wavelengths: {train_dataset.get_wavelengths()[:5]}...{train_dataset.get_wavelengths()[-5:]}')
|
| 318 |
+
if len(train_dataset) > 0:
|
| 319 |
+
(hsi, label) = train_dataset[0]
|
| 320 |
+
print(f'HSI shape: {hsi.shape}')
|
| 321 |
+
print(f'Label shape: {label.shape}')
|
| 322 |
+
print(f'Label unique values: {torch.unique(label)}')
|
dataloader/minneapple.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import numpy as np
|
| 3 |
+
import torch
|
| 4 |
+
import random
|
| 5 |
+
import cv2
|
| 6 |
+
import h5py
|
| 7 |
+
from PIL import Image
|
| 8 |
+
from torch.utils.data.dataset import Dataset
|
| 9 |
+
from torchvision import transforms
|
| 10 |
+
|
| 11 |
+
class MinneAppleHSIDataset(Dataset):
|
| 12 |
+
|
| 13 |
+
def __init__(self, root_dir, input_shape, train=True, augment=True):
|
| 14 |
+
self.root_dir = root_dir
|
| 15 |
+
self.input_shape = input_shape
|
| 16 |
+
self.train = train
|
| 17 |
+
self.augment = augment and train
|
| 18 |
+
self.channels = 129
|
| 19 |
+
self.lam = np.linspace(400, 1000, 129)
|
| 20 |
+
split = 'train' if self.train else 'test'
|
| 21 |
+
self.image_dir = os.path.join(root_dir, split, 'hsi')
|
| 22 |
+
self.mask_dir = os.path.join(root_dir, split, 'label')
|
| 23 |
+
self.images = list(sorted([f for f in os.listdir(self.image_dir) if f.lower().endswith('.mat')]))
|
| 24 |
+
print(f'[MinneAppleHSI] Loaded {len(self.images)} samples from {split}')
|
| 25 |
+
|
| 26 |
+
def __len__(self):
|
| 27 |
+
return len(self.images)
|
| 28 |
+
|
| 29 |
+
def __getitem__(self, idx):
|
| 30 |
+
(h, w) = self.input_shape
|
| 31 |
+
img_name = self.images[idx]
|
| 32 |
+
img_path = os.path.join(self.image_dir, img_name)
|
| 33 |
+
mask_name = os.path.splitext(img_name)[0] + '.png'
|
| 34 |
+
mask_path = os.path.join(self.mask_dir, mask_name)
|
| 35 |
+
with h5py.File(img_path, 'r') as f:
|
| 36 |
+
if 'cube' in f:
|
| 37 |
+
hsi = np.array(f['cube'])
|
| 38 |
+
elif 'data' in f:
|
| 39 |
+
hsi = np.array(f['data'])
|
| 40 |
+
elif 'hsi' in f:
|
| 41 |
+
hsi = np.array(f['hsi'])
|
| 42 |
+
else:
|
| 43 |
+
key = list(f.keys())[0]
|
| 44 |
+
hsi = np.array(f[key])
|
| 45 |
+
if hsi.ndim == 3:
|
| 46 |
+
if hsi.shape[0] == self.channels:
|
| 47 |
+
pass
|
| 48 |
+
elif hsi.shape[2] == self.channels:
|
| 49 |
+
hsi = np.transpose(hsi, (2, 0, 1))
|
| 50 |
+
elif hsi.shape[1] == self.channels:
|
| 51 |
+
hsi = np.transpose(hsi, (1, 0, 2))
|
| 52 |
+
hsi = hsi.astype(np.float32)
|
| 53 |
+
mask = cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE)
|
| 54 |
+
if mask is None:
|
| 55 |
+
raise FileNotFoundError(f'Mask not found: {mask_path}')
|
| 56 |
+
(c, orig_h, orig_w) = hsi.shape
|
| 57 |
+
if orig_h != h or orig_w != w:
|
| 58 |
+
resized_hsi = np.empty((c, h, w), dtype=np.float32)
|
| 59 |
+
for i in range(c):
|
| 60 |
+
resized_hsi[i] = cv2.resize(hsi[i], (w, h), interpolation=cv2.INTER_LINEAR)
|
| 61 |
+
hsi = resized_hsi
|
| 62 |
+
mask = cv2.resize(mask, (w, h), interpolation=cv2.INTER_NEAREST)
|
| 63 |
+
if self.augment:
|
| 64 |
+
(hsi, mask) = self._augment(hsi, mask)
|
| 65 |
+
mask[mask > 0] = 1
|
| 66 |
+
hsi = torch.tensor(hsi, dtype=torch.float32)
|
| 67 |
+
mask = torch.tensor(mask, dtype=torch.uint8)
|
| 68 |
+
return (hsi, mask)
|
| 69 |
+
|
| 70 |
+
def _augment(self, hsi, mask):
|
| 71 |
+
if random.random() > 0.5:
|
| 72 |
+
hsi = np.flip(hsi, axis=2).copy()
|
| 73 |
+
mask = cv2.flip(mask, 1)
|
| 74 |
+
if random.random() > 0.5:
|
| 75 |
+
hsi = np.flip(hsi, axis=1).copy()
|
| 76 |
+
mask = cv2.flip(mask, 0)
|
| 77 |
+
if random.random() > 0.5:
|
| 78 |
+
k = random.choice([1, 2, 3])
|
| 79 |
+
hsi = np.rot90(hsi, k, axes=(1, 2)).copy()
|
| 80 |
+
mask = np.rot90(mask, k)
|
| 81 |
+
mask = np.ascontiguousarray(mask)
|
| 82 |
+
return (hsi, mask)
|
| 83 |
+
|
| 84 |
+
class MinneAppleDataset(Dataset):
|
| 85 |
+
|
| 86 |
+
def __init__(self, root_dir, input_shape, train=True, augment=True):
|
| 87 |
+
self.root_dir = root_dir
|
| 88 |
+
self.input_shape = input_shape
|
| 89 |
+
self.train = train
|
| 90 |
+
self.augment = augment and train
|
| 91 |
+
self.channels = 3
|
| 92 |
+
split = 'train' if self.train else 'test'
|
| 93 |
+
self.image_dir = os.path.join(root_dir, split, 'images')
|
| 94 |
+
self.mask_dir = os.path.join(root_dir, split, 'masks')
|
| 95 |
+
self.images = list(sorted([f for f in os.listdir(self.image_dir) if f.endswith(('.png', '.jpg', '.jpeg'))]))
|
| 96 |
+
self.mean = [0.485, 0.456, 0.406]
|
| 97 |
+
self.std = [0.229, 0.224, 0.225]
|
| 98 |
+
self.transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize(mean=self.mean, std=self.std)])
|
| 99 |
+
|
| 100 |
+
def __len__(self):
|
| 101 |
+
return len(self.images)
|
| 102 |
+
|
| 103 |
+
def __getitem__(self, idx):
|
| 104 |
+
(h, w) = self.input_shape
|
| 105 |
+
img_name = self.images[idx]
|
| 106 |
+
img_path = os.path.join(self.image_dir, img_name)
|
| 107 |
+
mask_name = img_name.replace('.jpg', '.png').replace('.jpeg', '.png')
|
| 108 |
+
mask_path = os.path.join(self.mask_dir, mask_name)
|
| 109 |
+
image = cv2.imread(img_path)
|
| 110 |
+
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
| 111 |
+
mask = cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE)
|
| 112 |
+
image = cv2.resize(image, (w, h), interpolation=cv2.INTER_LINEAR)
|
| 113 |
+
mask = cv2.resize(mask, (w, h), interpolation=cv2.INTER_NEAREST)
|
| 114 |
+
if self.augment:
|
| 115 |
+
(image, mask) = self._augment(image, mask)
|
| 116 |
+
mask[mask > 0] = 1
|
| 117 |
+
image = image.astype(np.float32) / 255.0
|
| 118 |
+
image = np.transpose(image, (2, 0, 1))
|
| 119 |
+
image = torch.tensor(image, dtype=torch.float32)
|
| 120 |
+
for c in range(3):
|
| 121 |
+
image[c] = (image[c] - self.mean[c]) / self.std[c]
|
| 122 |
+
mask = torch.tensor(mask, dtype=torch.uint8)
|
| 123 |
+
return (image, mask)
|
| 124 |
+
|
| 125 |
+
def _augment(self, image, mask):
|
| 126 |
+
if random.random() > 0.5:
|
| 127 |
+
image = cv2.flip(image, 1)
|
| 128 |
+
mask = cv2.flip(mask, 1)
|
| 129 |
+
if random.random() > 0.5:
|
| 130 |
+
image = cv2.flip(image, 0)
|
| 131 |
+
mask = cv2.flip(mask, 0)
|
| 132 |
+
if random.random() > 0.5:
|
| 133 |
+
k = random.choice([1, 2, 3])
|
| 134 |
+
image = np.rot90(image, k)
|
| 135 |
+
mask = np.rot90(mask, k)
|
| 136 |
+
if random.random() > 0.5:
|
| 137 |
+
brightness = random.uniform(0.8, 1.2)
|
| 138 |
+
image = np.clip(image * brightness, 0, 255).astype(np.uint8)
|
| 139 |
+
image = np.ascontiguousarray(image)
|
| 140 |
+
mask = np.ascontiguousarray(mask)
|
| 141 |
+
return (image, mask)
|
| 142 |
+
|
| 143 |
+
class MinneAppleDatasetRaw(Dataset):
|
| 144 |
+
|
| 145 |
+
def __init__(self, root_dir, input_shape, train=True, augment=True):
|
| 146 |
+
self.root_dir = root_dir
|
| 147 |
+
self.input_shape = input_shape
|
| 148 |
+
self.train = train
|
| 149 |
+
self.augment = augment and train
|
| 150 |
+
self.channels = 3
|
| 151 |
+
split = 'train' if self.train else 'test'
|
| 152 |
+
self.image_dir = os.path.join(root_dir, split, 'images')
|
| 153 |
+
self.mask_dir = os.path.join(root_dir, split, 'masks')
|
| 154 |
+
self.images = list(sorted([f for f in os.listdir(self.image_dir) if f.endswith(('.png', '.jpg', '.jpeg'))]))
|
| 155 |
+
|
| 156 |
+
def __len__(self):
|
| 157 |
+
return len(self.images)
|
| 158 |
+
|
| 159 |
+
def __getitem__(self, idx):
|
| 160 |
+
(h, w) = self.input_shape
|
| 161 |
+
img_name = self.images[idx]
|
| 162 |
+
img_path = os.path.join(self.image_dir, img_name)
|
| 163 |
+
mask_name = img_name.replace('.jpg', '.png').replace('.jpeg', '.png')
|
| 164 |
+
mask_path = os.path.join(self.mask_dir, mask_name)
|
| 165 |
+
image = cv2.imread(img_path)
|
| 166 |
+
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
| 167 |
+
mask = cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE)
|
| 168 |
+
image = cv2.resize(image, (w, h), interpolation=cv2.INTER_LINEAR)
|
| 169 |
+
mask = cv2.resize(mask, (w, h), interpolation=cv2.INTER_NEAREST)
|
| 170 |
+
if self.augment:
|
| 171 |
+
(image, mask) = self._augment(image, mask)
|
| 172 |
+
mask[mask > 0] = 1
|
| 173 |
+
image = image.astype(np.float32) / 255.0
|
| 174 |
+
image = np.transpose(image, (2, 0, 1))
|
| 175 |
+
image = torch.tensor(image, dtype=torch.float32)
|
| 176 |
+
mask = torch.tensor(mask, dtype=torch.uint8)
|
| 177 |
+
return (image, mask)
|
| 178 |
+
|
| 179 |
+
def _augment(self, image, mask):
|
| 180 |
+
if random.random() > 0.5:
|
| 181 |
+
image = cv2.flip(image, 1)
|
| 182 |
+
mask = cv2.flip(mask, 1)
|
| 183 |
+
if random.random() > 0.5:
|
| 184 |
+
image = cv2.flip(image, 0)
|
| 185 |
+
mask = cv2.flip(mask, 0)
|
| 186 |
+
if random.random() > 0.5:
|
| 187 |
+
k = random.choice([1, 2, 3])
|
| 188 |
+
image = np.rot90(image, k)
|
| 189 |
+
mask = np.rot90(mask, k)
|
| 190 |
+
if random.random() > 0.5:
|
| 191 |
+
brightness = random.uniform(0.8, 1.2)
|
| 192 |
+
image = np.clip(image * brightness, 0, 255).astype(np.uint8)
|
| 193 |
+
image = np.ascontiguousarray(image)
|
| 194 |
+
mask = np.ascontiguousarray(mask)
|
| 195 |
+
return (image, mask)
|
dataloader/minneapple_ninja.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""MinnApple DatasetNinja loaders for detection (seg) and counting tasks."""
|
| 2 |
+
|
| 3 |
+
import base64
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
import zlib
|
| 7 |
+
|
| 8 |
+
import cv2
|
| 9 |
+
import numpy as np
|
| 10 |
+
import torch
|
| 11 |
+
from torch.utils.data import Dataset
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _decode_bitmap(obj, h, w):
|
| 15 |
+
"""Decode DatasetNinja bitmap mask to [H, W] uint8."""
|
| 16 |
+
if obj.get('geometryType') != 'bitmap':
|
| 17 |
+
return None
|
| 18 |
+
origin = obj['bitmap']['origin']
|
| 19 |
+
ox, oy = int(origin[0]), int(origin[1])
|
| 20 |
+
raw = base64.b64decode(obj['bitmap']['data'])
|
| 21 |
+
try:
|
| 22 |
+
raw = zlib.decompress(raw)
|
| 23 |
+
except zlib.error:
|
| 24 |
+
pass
|
| 25 |
+
bm = cv2.imdecode(np.frombuffer(raw, np.uint8), cv2.IMREAD_UNCHANGED)
|
| 26 |
+
if bm is None:
|
| 27 |
+
return None
|
| 28 |
+
if bm.ndim == 3:
|
| 29 |
+
bm = bm[:, :, 0]
|
| 30 |
+
mask = np.zeros((h, w), dtype=np.uint8)
|
| 31 |
+
bh, bw = bm.shape[:2]
|
| 32 |
+
y1, x1 = oy, ox
|
| 33 |
+
y2, x2 = min(oy + bh, h), min(ox + bw, w)
|
| 34 |
+
mask[y1:y2, x1:x2] = np.maximum(mask[y1:y2, x1:x2], bm[:y2 - y1, :x2 - x1])
|
| 35 |
+
return mask
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class MinneAppleDetectionDataset(Dataset):
|
| 39 |
+
"""Detection via instance bitmap -> semantic mask.
|
| 40 |
+
|
| 41 |
+
Note: detection-test in DatasetNinja has empty annotations.
|
| 42 |
+
We hold out 15% of detection-train as validation.
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
TRAIN_RATIO = 0.85
|
| 46 |
+
|
| 47 |
+
def __init__(self, root, split='train', img_size=(512, 512), seed=42):
|
| 48 |
+
self.root = root
|
| 49 |
+
self.img_size = img_size
|
| 50 |
+
img_dir = os.path.join(root, 'detection-train', 'img')
|
| 51 |
+
ann_dir = os.path.join(root, 'detection-train', 'ann')
|
| 52 |
+
all_files = sorted([f for f in os.listdir(img_dir)
|
| 53 |
+
if f.lower().endswith(('.png', '.jpg', '.jpeg'))])
|
| 54 |
+
rng = np.random.RandomState(seed)
|
| 55 |
+
idx = rng.permutation(len(all_files))
|
| 56 |
+
n_train = int(len(all_files) * self.TRAIN_RATIO)
|
| 57 |
+
if split == 'train':
|
| 58 |
+
self.files = [all_files[i] for i in idx[:n_train]]
|
| 59 |
+
elif split in ('val', 'test'):
|
| 60 |
+
self.files = [all_files[i] for i in idx[n_train:]]
|
| 61 |
+
else:
|
| 62 |
+
raise ValueError(f"split must be train/val/test, got {split}")
|
| 63 |
+
self.img_dir = img_dir
|
| 64 |
+
self.ann_dir = ann_dir
|
| 65 |
+
|
| 66 |
+
def __len__(self):
|
| 67 |
+
return len(self.files)
|
| 68 |
+
|
| 69 |
+
def __getitem__(self, idx):
|
| 70 |
+
name = self.files[idx]
|
| 71 |
+
img = cv2.imread(os.path.join(self.img_dir, name))
|
| 72 |
+
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
| 73 |
+
h0, w0 = img.shape[:2]
|
| 74 |
+
ann_path = os.path.join(self.ann_dir, name + '.json')
|
| 75 |
+
mask = np.zeros((h0, w0), dtype=np.uint8)
|
| 76 |
+
if os.path.isfile(ann_path):
|
| 77 |
+
ann = json.load(open(ann_path))
|
| 78 |
+
for obj in ann.get('objects', []):
|
| 79 |
+
bm = _decode_bitmap(obj, h0, w0)
|
| 80 |
+
if bm is not None:
|
| 81 |
+
mask = np.maximum(mask, (bm > 0).astype(np.uint8))
|
| 82 |
+
h, w = self.img_size
|
| 83 |
+
img = cv2.resize(img, (w, h), interpolation=cv2.INTER_LINEAR)
|
| 84 |
+
mask = cv2.resize(mask, (w, h), interpolation=cv2.INTER_NEAREST)
|
| 85 |
+
img = torch.from_numpy(img.astype(np.float32) / 255.0).permute(2, 0, 1)
|
| 86 |
+
mask = torch.from_numpy(mask.astype(np.uint8))
|
| 87 |
+
return img, mask
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class MinneAppleCountingDataset(Dataset):
|
| 91 |
+
"""Apple counting on fixed-size patches."""
|
| 92 |
+
|
| 93 |
+
SPLITS = {
|
| 94 |
+
'train': 'counting-train',
|
| 95 |
+
'val': 'counting-val',
|
| 96 |
+
'test': 'counting-test',
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
def __init__(self, root, split='train', img_size=(128, 128), max_samples=-1):
|
| 100 |
+
self.root = root
|
| 101 |
+
sub = self.SPLITS[split]
|
| 102 |
+
self.img_dir = os.path.join(root, sub, 'img')
|
| 103 |
+
self.ann_dir = os.path.join(root, sub, 'ann')
|
| 104 |
+
self.img_size = img_size
|
| 105 |
+
self.files = sorted([f for f in os.listdir(self.img_dir)
|
| 106 |
+
if f.lower().endswith('.png')])
|
| 107 |
+
if max_samples > 0:
|
| 108 |
+
self.files = self.files[:max_samples]
|
| 109 |
+
|
| 110 |
+
def __len__(self):
|
| 111 |
+
return len(self.files)
|
| 112 |
+
|
| 113 |
+
def __getitem__(self, idx):
|
| 114 |
+
name = self.files[idx]
|
| 115 |
+
img = cv2.imread(os.path.join(self.img_dir, name))
|
| 116 |
+
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
| 117 |
+
ann = json.load(open(os.path.join(self.ann_dir, name + '.json')))
|
| 118 |
+
count = 0
|
| 119 |
+
for t in ann.get('tags', []):
|
| 120 |
+
if t.get('name') == 'count':
|
| 121 |
+
count = int(t.get('value', 0))
|
| 122 |
+
h, w = self.img_size
|
| 123 |
+
img = cv2.resize(img, (w, h), interpolation=cv2.INTER_LINEAR)
|
| 124 |
+
img = torch.from_numpy(img.astype(np.float32) / 255.0).permute(2, 0, 1)
|
| 125 |
+
return img, torch.tensor(count, dtype=torch.float32)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def detection_metrics(pred_mask, gt_mask):
|
| 129 |
+
"""Binary seg metrics for detection task."""
|
| 130 |
+
pred = (pred_mask > 0).astype(np.uint8)
|
| 131 |
+
gt = (gt_mask > 0).astype(np.uint8)
|
| 132 |
+
inter = (pred & gt).sum()
|
| 133 |
+
union = ((pred | gt)).sum()
|
| 134 |
+
iou = inter / (union + 1e-8)
|
| 135 |
+
tp = inter
|
| 136 |
+
fp = pred.sum() - tp
|
| 137 |
+
fn = gt.sum() - tp
|
| 138 |
+
prec = tp / (tp + fp + 1e-8)
|
| 139 |
+
rec = tp / (tp + fn + 1e-8)
|
| 140 |
+
f1 = 2 * prec * rec / (prec + rec + 1e-8)
|
| 141 |
+
return {'iou': float(iou), 'precision': float(prec), 'recall': float(rec), 'f1': float(f1)}
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def counting_metrics(pred_counts, gt_counts):
|
| 145 |
+
pred = np.asarray(pred_counts, dtype=np.float64)
|
| 146 |
+
gt = np.asarray(gt_counts, dtype=np.float64)
|
| 147 |
+
mae = np.abs(pred - gt).mean()
|
| 148 |
+
rmse = np.sqrt(((pred - gt) ** 2).mean())
|
| 149 |
+
return {'MAE': float(mae), 'RMSE': float(rmse)}
|
dataloader/modid.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import numpy as np
|
| 3 |
+
import torch
|
| 4 |
+
import random
|
| 5 |
+
import json
|
| 6 |
+
import matplotlib.pyplot as plt
|
| 7 |
+
import h5py
|
| 8 |
+
import scipy.io
|
| 9 |
+
import cv2
|
| 10 |
+
from PIL import Image, ImageEnhance
|
| 11 |
+
from torch.utils.data.dataset import Dataset
|
| 12 |
+
from torchvision import transforms
|
| 13 |
+
import spectral
|
| 14 |
+
|
| 15 |
+
class ModidDataset(object):
|
| 16 |
+
|
| 17 |
+
def __init__(self, root_dir, input_shape, train):
|
| 18 |
+
self.root_dir = root_dir
|
| 19 |
+
self.input_shape = input_shape
|
| 20 |
+
self.train = train
|
| 21 |
+
self.channels = 16
|
| 22 |
+
self.lam = np.array([460.48099, 465.215098, 474.1194, 482.578653, 492.59933, 504.367465, 512.469275, 521.987657, 533.930667, 541.203169, 551.996143, 559.719978, 570.1331, 579.729623, 585.387574, 595.018809])
|
| 23 |
+
if self.train:
|
| 24 |
+
data_dir = os.path.join(root_dir, 'train', 'data')
|
| 25 |
+
label_dir = os.path.join(root_dir, 'train', 'label')
|
| 26 |
+
else:
|
| 27 |
+
data_dir = os.path.join(root_dir, 'test', 'data')
|
| 28 |
+
label_dir = os.path.join(root_dir, 'test', 'label')
|
| 29 |
+
self.hsi = list(sorted([f for f in os.listdir(data_dir) if f.lower().endswith('.hdr')]))
|
| 30 |
+
self.label = list(sorted([f for f in os.listdir(label_dir) if f.lower().endswith('.png')]))
|
| 31 |
+
self.data_dir = data_dir
|
| 32 |
+
self.label_dir = label_dir
|
| 33 |
+
|
| 34 |
+
def __getitem__(self, idx):
|
| 35 |
+
(h, w) = self.input_shape
|
| 36 |
+
hsi_path = os.path.join(self.data_dir, self.hsi[idx])
|
| 37 |
+
label_path = os.path.join(self.label_dir, self.label[idx])
|
| 38 |
+
image = spectral.open_image(hsi_path)
|
| 39 |
+
cube = np.transpose(image.load(), (2, 0, 1))
|
| 40 |
+
hsi = np.array(cube, dtype=np.float32)
|
| 41 |
+
(c, orig_h, orig_w) = hsi.shape
|
| 42 |
+
if orig_h != h or orig_w != w:
|
| 43 |
+
resized_hsi = np.empty((c, h, w), dtype=np.float32)
|
| 44 |
+
for i in range(c):
|
| 45 |
+
resized_hsi[i] = cv2.resize(hsi[i], (w, h), interpolation=cv2.INTER_LINEAR)
|
| 46 |
+
hsi = resized_hsi
|
| 47 |
+
label_image = cv2.imread(label_path, cv2.IMREAD_GRAYSCALE)
|
| 48 |
+
if label_image.shape[0] != h or label_image.shape[1] != w:
|
| 49 |
+
label_image = cv2.resize(label_image, (w, h), interpolation=cv2.INTER_NEAREST)
|
| 50 |
+
label_image[label_image != 0] = 1
|
| 51 |
+
label = torch.tensor(label_image, dtype=torch.uint8)
|
| 52 |
+
return (hsi, label)
|
| 53 |
+
|
| 54 |
+
def __len__(self):
|
| 55 |
+
return len(self.label)
|
| 56 |
+
|
| 57 |
+
def random_flip_LR(self, hsi_one_channel_list, rgb, label):
|
| 58 |
+
if random.random() > 0.5:
|
| 59 |
+
for index in range(len(hsi_one_channel_list)):
|
| 60 |
+
hsi_one_channel_list[index] = hsi_one_channel_list[index].transpose(Image.FLIP_LEFT_RIGHT)
|
| 61 |
+
rgb = rgb.transpose(Image.FLIP_LEFT_RIGHT)
|
| 62 |
+
label = label.transpose(Image.FLIP_LEFT_RIGHT)
|
| 63 |
+
return (hsi_one_channel_list, rgb, label)
|
| 64 |
+
|
| 65 |
+
def random_flip_UD(self, hsi_one_channel_list, rgb, label):
|
| 66 |
+
if random.random() > 0.5:
|
| 67 |
+
for index in range(len(hsi_one_channel_list)):
|
| 68 |
+
hsi_one_channel_list[index] = hsi_one_channel_list[index].transpose(Image.FLIP_TOP_BOTTOM)
|
| 69 |
+
rgb = rgb.transpose(Image.FLIP_TOP_BOTTOM)
|
| 70 |
+
label = label.transpose(Image.FLIP_TOP_BOTTOM)
|
| 71 |
+
return (hsi_one_channel_list, rgb, label)
|
| 72 |
+
|
| 73 |
+
def get_params(self, low):
|
| 74 |
+
(self.h, self.w) = low.size
|
| 75 |
+
self.crop_height = 128
|
| 76 |
+
self.crop_width = 128
|
| 77 |
+
i = random.randint(0, self.h - self.crop_height)
|
| 78 |
+
j = random.randint(0, self.w - self.crop_width)
|
| 79 |
+
return (i, j)
|
| 80 |
+
|
| 81 |
+
def Random_Crop(self, hsi_one_channel_list, rgb, label):
|
| 82 |
+
(self.i, self.j) = self.get_params(rgb)
|
| 83 |
+
if random.random() > 0.5:
|
| 84 |
+
rgb = rgb.crop((self.j, self.i, self.j + self.crop_width, self.i + self.crop_height))
|
| 85 |
+
label = label.crop((self.j, self.i, self.j + self.crop_width, self.i + self.crop_height))
|
| 86 |
+
for index in range(len(hsi_one_channel_list)):
|
| 87 |
+
hsi_one_channel_list[index] = hsi_one_channel_list[index].crop((self.j, self.i, self.j + self.crop_width, self.i + self.crop_height))
|
| 88 |
+
return (hsi_one_channel_list, rgb, label)
|
datasets/.gitkeep
ADDED
|
File without changes
|
docs/.nojekyll
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
|
docs/assets/favicon.png
ADDED
|
|
docs/assets/palevision-fish.png
ADDED
|
Git LFS Details
|
docs/assets/thumbnail.jpg
ADDED
|
|
Git LFS Details
|
docs/index.html
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!doctype html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="utf-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
| 6 |
+
<title>Paleoinspired Vision | PaleVision</title>
|
| 7 |
+
<meta name="description" content="Paleoinspired Vision: From Exploring Colour Vision Evolution to Inspiring Camera Design. Learnable opsin spectral responses connect evolutionary biology and task-specific imaging.">
|
| 8 |
+
<link rel="canonical" href="https://luyijie-research.github.io/PaleVision/">
|
| 9 |
+
<link rel="icon" type="image/png" sizes="64x64" href="assets/favicon.png">
|
| 10 |
+
<link rel="apple-touch-icon" href="assets/palevision-fish.png">
|
| 11 |
+
<meta property="og:type" content="website">
|
| 12 |
+
<meta property="og:site_name" content="PaleVision">
|
| 13 |
+
<meta property="og:title" content="Paleoinspired Vision">
|
| 14 |
+
<meta property="og:description" content="From Exploring Colour Vision Evolution to Inspiring Camera Design">
|
| 15 |
+
<meta property="og:url" content="https://luyijie-research.github.io/PaleVision/">
|
| 16 |
+
<meta property="og:image" content="https://luyijie-research.github.io/PaleVision/assets/thumbnail.jpg">
|
| 17 |
+
<meta property="og:image:secure_url" content="https://luyijie-research.github.io/PaleVision/assets/thumbnail.jpg">
|
| 18 |
+
<meta property="og:image:type" content="image/jpeg">
|
| 19 |
+
<meta property="og:image:width" content="1280">
|
| 20 |
+
<meta property="og:image:height" content="581">
|
| 21 |
+
<meta property="og:image:alt" content="A blue fish and spectral light illustrate the connection between colour vision and camera filter design.">
|
| 22 |
+
<meta name="twitter:card" content="summary_large_image">
|
| 23 |
+
<meta name="twitter:title" content="Paleoinspired Vision">
|
| 24 |
+
<meta name="twitter:description" content="From Exploring Colour Vision Evolution to Inspiring Camera Design">
|
| 25 |
+
<meta name="twitter:image" content="https://luyijie-research.github.io/PaleVision/assets/thumbnail.jpg">
|
| 26 |
+
<meta name="twitter:image:alt" content="A blue fish and spectral light illustrate the connection between colour vision and camera filter design.">
|
| 27 |
+
<meta name="theme-color" content="#fafbf9">
|
| 28 |
+
<style>
|
| 29 |
+
:root{--ink:#19302c;--muted:#64726e;--green:#376a57;--line:#dce5df;--paper:#fafbf9;--blue:#eaf3f8;--mint:#eef5ed;--rose:#faf0eb}
|
| 30 |
+
*{box-sizing:border-box}html{scroll-behavior:smooth;scroll-padding-top:88px}body{margin:0;background:var(--paper);color:var(--ink);font-family:Arial,Helvetica,sans-serif;-webkit-font-smoothing:antialiased;line-height:1.65}
|
| 31 |
+
a{color:inherit;text-decoration:none}a:focus-visible,button:focus-visible{outline:3px solid #699fd1;outline-offset:5px}button{font:inherit}::selection{background:#d9eadf}
|
| 32 |
+
.wrap{max-width:1080px;margin:auto;padding:0 32px}nav{border-bottom:1px solid var(--line);background:rgba(250,251,249,.96);position:sticky;top:0;z-index:10}
|
| 33 |
+
.nav-inner{height:70px;display:flex;align-items:center;justify-content:space-between;gap:20px}.brand{display:inline-flex;align-items:center;gap:10px;flex-shrink:0;font-size:19px;font-weight:700;letter-spacing:-.6px}.brand-icon{display:block;width:46px;height:46px;object-fit:contain}.brand-name{white-space:nowrap}.brand-name span{color:var(--green)}.nav-links{display:flex;gap:26px;font-size:13px;color:var(--muted)}.nav-links a:hover{color:var(--green)}
|
| 34 |
+
header{text-align:center;padding:68px 0 34px}.eyebrow{display:inline-flex;align-items:center;gap:9px;color:var(--green);font-size:12px;letter-spacing:1.5px}.dot{width:7px;height:7px;border-radius:50%;background:var(--green)}
|
| 35 |
+
h1{font-family:Georgia,'Times New Roman',serif;font-weight:400;font-size:clamp(42px,6.5vw,72px);line-height:1.12;letter-spacing:-2.4px;margin:23px 0 16px;text-wrap:balance}
|
| 36 |
+
.subtitle{font-size:clamp(19px,2.6vw,27px);line-height:1.4;letter-spacing:-.5px;max-width:800px;margin:0 auto 28px;text-wrap:balance}
|
| 37 |
+
.venue{font-size:14px;font-weight:600;color:var(--green);margin:-10px 0 22px}
|
| 38 |
+
.authors{font-size:14px;max-width:860px;margin:0 auto 14px;line-height:2.1;text-wrap:balance}.authors span{display:inline-block;margin:0 7px}.authors sup{font-size:9px;color:var(--green);margin-left:2px}
|
| 39 |
+
.affiliations{max-width:850px;margin:auto;font-size:11px;color:var(--muted);line-height:1.9;text-wrap:balance}.affiliations span{display:inline-block;margin:0 7px}.correspondence{font-size:11px;color:var(--muted);margin:11px 0 0}
|
| 40 |
+
.buttons{display:flex;justify-content:center;gap:12px;flex-wrap:wrap;margin-top:25px}.btn{display:inline-flex;align-items:center;justify-content:center;gap:8px;min-height:44px;padding:10px 22px;border-radius:6px;border:1px solid var(--line);font-size:13px;font-weight:600;background:white}.btn.primary{background:var(--ink);border-color:var(--ink);color:white}.btn:hover{transform:translateY(-1px);box-shadow:0 4px 14px #19302c12}
|
| 41 |
+
.hero{margin:0;padding:16px 0 40px}.image-shell{overflow:hidden;border:1px solid var(--line);border-radius:12px;background:white;padding:8px;box-shadow:0 12px 40px #19302c08}.hero img{display:block;width:100%;height:auto;border-radius:6px}.hero figcaption{text-align:center;color:var(--muted);font-size:12px;margin:16px auto 0;max-width:680px;text-wrap:balance}
|
| 42 |
+
section{padding:48px 0;border-top:1px solid var(--line)}.section-heading{display:flex;align-items:baseline;gap:20px;margin-bottom:23px}.section-num{color:var(--green);font-size:12px;font-weight:600}h2{font:400 34px/1.25 Georgia,'Times New Roman',serif;letter-spacing:-.7px;margin:0}
|
| 43 |
+
.lead{font:400 26px/1.5 Georgia,'Times New Roman',serif;max-width:900px;margin:0 0 24px;text-wrap:pretty}.body-copy{color:#4b5d56;font-size:15px;line-height:1.9;max-width:920px;text-wrap:pretty}.body-copy p{margin:0 0 18px}.cards{display:grid;grid-template-columns:repeat(3,1fr);gap:18px;margin-top:28px}.card{padding:27px 24px;border-radius:10px}.card:nth-child(1){background:var(--blue)}.card:nth-child(2){background:var(--mint)}.card:nth-child(3){background:var(--rose)}.card .step{font-size:11px;color:var(--muted)}h3{font-size:17px;line-height:1.4;letter-spacing:-.3px;margin:18px 0 12px}.card p{font-size:13px;line-height:1.8;color:#4b5d56;margin:0;text-wrap:pretty}
|
| 44 |
+
.research{display:grid;grid-template-columns:1fr 1fr;gap:32px}.research p{font-size:14px;color:#4b5d56;line-height:1.9;text-wrap:pretty}.research h3{margin-top:0}.text-link{font-size:13px;font-weight:600;color:var(--green);border-bottom:1px solid #9db8a9;padding-bottom:3px}
|
| 45 |
+
.code-box{position:relative;border:1px solid var(--line);background:#f0f4ef;border-radius:9px;padding:24px;margin:20px 0}pre{font:12px/1.8 ui-monospace,SFMono-Regular,Consolas,monospace;white-space:pre-wrap;overflow-wrap:anywhere;margin:0;color:#3e564b}.copy{position:absolute;top:12px;right:12px;background:white;border:1px solid var(--line);border-radius:4px;padding:5px 11px;font-size:11px;color:var(--muted);cursor:pointer}.citation pre{padding-right:46px}
|
| 46 |
+
footer{border-top:1px solid var(--line);padding:26px 0 34px;color:var(--muted);font-size:11px}.footer-inner{display:flex;justify-content:space-between;gap:15px;flex-wrap:wrap}
|
| 47 |
+
@media(max-width:700px){.wrap{padding:0 21px}.nav-inner{height:60px}.nav-links{gap:16px;font-size:12px}.nav-links .desktop{display:none}header{padding-top:43px}h1{letter-spacing:-1.6px}.authors{font-size:12px}.affiliations{font-size:10px}.cards,.research{grid-template-columns:1fr}.cards{gap:12px}.card{padding:23px}.card h3{margin-top:9px}.lead{font-size:23px}section{padding:35px 0}h2{font-size:29px}.hero{padding-bottom:30px}.image-shell{padding:4px;border-radius:8px}.hero figcaption{font-size:11px}.body-copy{font-size:14px}.citation pre{padding-right:0;padding-top:24px}}
|
| 48 |
+
@media(max-width:480px){.brand-icon{width:38px;height:38px}.brand{gap:8px}.nav-links a[href="#overview"]{display:none}.nav-inner{gap:12px}}
|
| 49 |
+
@media(prefers-reduced-motion:reduce){html{scroll-behavior:auto}.btn:hover{transform:none}}
|
| 50 |
+
</style>
|
| 51 |
+
</head>
|
| 52 |
+
<body>
|
| 53 |
+
<nav aria-label="Main navigation"><div class="wrap nav-inner">
|
| 54 |
+
<a class="brand" href="./" aria-label="PaleVision home"><img class="brand-icon" src="assets/palevision-fish.png" width="46" height="46" alt=""><span class="brand-name">Paleo<span>Vision</span></span></a>
|
| 55 |
+
<div class="nav-links"><a href="#overview">Overview</a><a class="desktop" href="#research">Research</a><a href="#code">Code</a><a href="https://github.com/luyijie-research/PaleVision">GitHub ↗</a></div>
|
| 56 |
+
</div></nav>
|
| 57 |
+
<main class="wrap">
|
| 58 |
+
<header>
|
| 59 |
+
<div class="eyebrow"><span class="dot"></span>Evolution · Perception · Imaging</div>
|
| 60 |
+
<h1>Paleoinspired Vision</h1>
|
| 61 |
+
<p class="subtitle">From Exploring Colour Vision Evolution<br>to Inspiring Camera Design</p>
|
| 62 |
+
<p class="venue">Accepted at NeurIPS 2026</p>
|
| 63 |
+
<p class="authors">
|
| 64 |
+
<span>Yijie Lu<sup>1</sup></span><span>Zhimin Zong<sup>2</sup></span><span>Junjie Zhang<sup>3</sup></span><span>Shenghan Su<sup>4</sup></span><span>Zeyun Zhao<sup>5</sup></span><span>Ziteng Cui<sup>4,6</sup></span><span>Yan Pu<sup>7</sup></span><span>Jing Lu<sup>7</sup></span><span>Daisuke Kojima<sup>6</sup></span><span>Lin Gu<sup>8,*</sup></span><span>Ruogu Fang<sup>5</sup></span>
|
| 65 |
+
</p>
|
| 66 |
+
<div class="affiliations">
|
| 67 |
+
<span><sup>1</sup> Peking University</span><span><sup>2</sup> University of Florida</span><span><sup>3</sup> The University of Hong Kong</span><span><sup>4</sup> The Hong Kong University of Science and Technology (Guangzhou)</span><span><sup>5</sup> Vanderbilt University</span><span><sup>6</sup> The University of Tokyo</span><span><sup>7</sup> Key Laboratory of Vertebrate Evolution and Human Origins, IVPP, Chinese Academy of Sciences</span><span><sup>8</sup> Tohoku University</span>
|
| 68 |
+
</div>
|
| 69 |
+
<p class="correspondence">* Corresponding author: <a href="mailto:lin@tohoku.ac.jp">Lin Gu</a></p>
|
| 70 |
+
<div class="buttons"><a class="btn primary" href="https://github.com/luyijie-research/PaleVision">View code ↗</a><a class="btn" href="#abstract">Read abstract ↓</a><a class="btn" href="#citation">Citation</a></div>
|
| 71 |
+
</header>
|
| 72 |
+
<figure class="hero">
|
| 73 |
+
<div class="image-shell"><img src="assets/thumbnail.jpg" width="1280" height="581" fetchpriority="high" alt="A blue fish and spectral light illustrate the connection between colour vision and camera filter design."></div>
|
| 74 |
+
<figcaption>Exploring how organisms perceive colour, and translating the principles of visual evolution into camera design.</figcaption>
|
| 75 |
+
</figure>
|
| 76 |
+
<section id="overview">
|
| 77 |
+
<div class="section-heading"><span class="section-num">01</span><h2>Vision shaped by evolution</h2></div>
|
| 78 |
+
<p class="lead">What can millions of years of colour vision evolution teach us about designing cameras?</p>
|
| 79 |
+
<div class="body-copy"><p>Paleoinspired Vision connects evolutionary biology with machine vision through a learnable model of opsin spectral sensitivity. Recognition performance provides a task-driven measure of evolutionary pressure, allowing us to explore how visual systems adapt to their environments and how these adaptations can inform imaging technology.</p></div>
|
| 80 |
+
<div class="cards">
|
| 81 |
+
<article class="card"><span class="step">Stage 1 · Perception</span><h3>Model the opsin response</h3><p>A learnable opsin layer transforms hyperspectral input into colour images, modelling a simplified version of visual transduction in the retina.</p></article>
|
| 82 |
+
<article class="card"><span class="step">Stage 2 · Evolution</span><h3>Explore visual adaptation</h3><p>Evolutionary conservation optimisation uses recognition performance to guide mutation-driven changes in spectral sensitivity.</p></article>
|
| 83 |
+
<article class="card"><span class="step">Stage 3 · Camera design</span><h3>Translate biology into imaging</h3><p>The learned spectral responses inform task-specific camera filters, connecting biological adaptation with application-driven design.</p></article>
|
| 84 |
+
</div>
|
| 85 |
+
</section>
|
| 86 |
+
<section id="abstract">
|
| 87 |
+
<div class="section-heading"><span class="section-num">02</span><h2>Abstract</h2></div>
|
| 88 |
+
<div class="body-copy">
|
| 89 |
+
<p>The evolution of colour vision is captivating, as it reveals the adaptive strategies of extinct species while simultaneously inspiring innovations in modern imaging technology. In this study, we present a simplified model of visual transduction in the retina, introducing a novel opsin layer. We quantify evolutionary pressures by measuring machine vision recognition accuracy on colour images shaped by specific opsins. Building on this, we develop an evolutionary conservation optimisation algorithm to reconstruct the spectral sensitivity of opsins, enabling mutation-driven adaptations to more effectively spot fruits or predators. This model condenses millions of years of evolution into seconds using GPU, providing an experimental framework to test long-standing hypotheses in evolutionary biology, such as vision of early mammals, primate trichromacy from gene duplication, retention of colour blindness, blue-shift of fish rod and multiple rod opsins with bioluminescence.</p>
|
| 90 |
+
<p>Beyond validating existing paleontological hypotheses, our model further enables speculative explorations of hypothetical species, such as organisms with visual systems adapted to Martian conditions. These constitute our contributions to AI for life science and neuroscience. Besides, the principles derived from these biological studies can translate into practical engineering solutions. In practice, our findings suggest a minimalist yet effective approach to task-specific camera filter design, optimising the spectral response function to meet application-driven demands.</p>
|
| 91 |
+
</div>
|
| 92 |
+
</section>
|
| 93 |
+
<section id="research">
|
| 94 |
+
<div class="section-heading"><span class="section-num">03</span><h2>From biological questions to engineering</h2></div>
|
| 95 |
+
<div class="research">
|
| 96 |
+
<article><h3>Revisiting colour vision evolution</h3><p>The framework investigates hypotheses spanning early mammalian vision, primate trichromacy, colour blindness, fish rod blue-shifts and multiple rod opsins in bioluminescent environments. Hypothetical Martian adaptations extend this exploration beyond existing species.</p></article>
|
| 97 |
+
<article><h3>Learning task-specific spectral responses</h3><p>The implementation includes evolutionary visual perception layers (EVPL), a MiT backbone and a SegFormer head for hyperspectral semantic segmentation. Learned spectral sensitivities provide a route toward camera filters tailored to recognition tasks.</p></article>
|
| 98 |
+
</div>
|
| 99 |
+
</section>
|
| 100 |
+
<section id="code">
|
| 101 |
+
<div class="section-heading"><span class="section-num">04</span><h2>Explore the implementation</h2></div>
|
| 102 |
+
<div class="body-copy"><p>The public repository contains model components, experiment configurations, dataset loaders and training entry points. Start with the README for environment setup and data preparation.</p></div>
|
| 103 |
+
<div class="code-box"><pre>git clone https://github.com/luyijie-research/PaleVision.git
|
| 104 |
+
cd PaleVision
|
| 105 |
+
conda create -n palevision python=3.10 -y
|
| 106 |
+
conda activate palevision
|
| 107 |
+
pip install -r requirements.txt</pre></div>
|
| 108 |
+
<a class="text-link" href="https://github.com/luyijie-research/PaleVision#readme">Installation and experiment instructions ↗</a>
|
| 109 |
+
</section>
|
| 110 |
+
<section id="citation" class="citation">
|
| 111 |
+
<div class="section-heading"><span class="section-num">05</span><h2>Citation</h2></div>
|
| 112 |
+
<div class="body-copy"><p>If you use PaleVision in your research, please cite our NeurIPS 2026 paper:</p></div>
|
| 113 |
+
<div class="code-box">
|
| 114 |
+
<button class="copy" type="button" id="copy-citation" aria-label="Copy BibTeX citation">Copy</button>
|
| 115 |
+
<pre id="bibtex">@inproceedings{lu2026paleoinspired,
|
| 116 |
+
title = {Paleoinspired Vision: From Exploring Colour Vision Evolution to Inspiring Camera Design},
|
| 117 |
+
author = {Lu, Yijie and Zong, Zhimin and Zhang, Junjie and Su, Shenghan and Zhao, Zeyun and Cui, Ziteng and Pu, Yan and Lu, Jing and Kojima, Daisuke and Gu, Lin and Fang, Ruogu},
|
| 118 |
+
booktitle = {Advances in Neural Information Processing Systems},
|
| 119 |
+
year = {2026},
|
| 120 |
+
url = {https://luyijie-research.github.io/PaleVision/}
|
| 121 |
+
}</pre>
|
| 122 |
+
</div>
|
| 123 |
+
<span id="copy-status" role="status" style="font-size:12px;color:var(--muted)"></span>
|
| 124 |
+
</section>
|
| 125 |
+
</main>
|
| 126 |
+
<footer><div class="wrap footer-inner"><span>PaleVision · Paleoinspired Vision</span><a href="https://github.com/luyijie-research/PaleVision">Project source on GitHub ↗</a></div></footer>
|
| 127 |
+
<script>
|
| 128 |
+
document.getElementById('copy-citation').addEventListener('click', async function () {
|
| 129 |
+
try {
|
| 130 |
+
await navigator.clipboard.writeText(document.getElementById('bibtex').textContent);
|
| 131 |
+
document.getElementById('copy-status').textContent = 'Citation copied.';
|
| 132 |
+
} catch (_) {
|
| 133 |
+
const range = document.createRange();
|
| 134 |
+
range.selectNodeContents(document.getElementById('bibtex'));
|
| 135 |
+
const selection = window.getSelection();
|
| 136 |
+
selection.removeAllRanges();
|
| 137 |
+
selection.addRange(range);
|
| 138 |
+
document.getElementById('copy-status').textContent = 'Select and copy the citation above.';
|
| 139 |
+
}
|
| 140 |
+
});
|
| 141 |
+
</script>
|
| 142 |
+
</body>
|
| 143 |
+
</html>
|
encoder_swap_exp.py
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Unified encoder-swap + opsin-mode experiment for MODID and MHSI.
|
| 3 |
+
|
| 4 |
+
Pipeline: HSI -> EVPL(opsin) -> Encoder -> SegFormerHead -> segmentation
|
| 5 |
+
|
| 6 |
+
Example:
|
| 7 |
+
torchrun --nproc_per_node=4 encoder_swap_exp.py \\
|
| 8 |
+
--dataset mhsi --encoder pvt_v2_b2 --opsin_mode free \\
|
| 9 |
+
--config configs/modid.yaml --workdir work_dir/enc_mhsi_pvt_free
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import argparse
|
| 13 |
+
import datetime
|
| 14 |
+
import json
|
| 15 |
+
import logging
|
| 16 |
+
import os
|
| 17 |
+
import random
|
| 18 |
+
import sys
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
import torch
|
| 22 |
+
import torch.distributed as dist
|
| 23 |
+
import torch.nn.functional as F
|
| 24 |
+
from omegaconf import OmegaConf
|
| 25 |
+
from torch.nn.parallel import DistributedDataParallel
|
| 26 |
+
from torch.utils.data import DataLoader
|
| 27 |
+
from torch.utils.data.distributed import DistributedSampler
|
| 28 |
+
from tqdm import tqdm
|
| 29 |
+
|
| 30 |
+
from dataloader.modid import ModidDataset
|
| 31 |
+
from dataloader.Data_Generate import Data_Generate_Bile
|
| 32 |
+
from models.backbone.encoder_factory import build_encoder, POST_SEGFORMER_ENCODERS, ENCODER_SPECS
|
| 33 |
+
from models.HSI_to_RGB.evpl_factory import build_evpl, OPSIN_MODES
|
| 34 |
+
from models.decoder.segformer_head import SegFormerHead
|
| 35 |
+
from util.optimizer import PolyWarmupAdamW
|
| 36 |
+
from util.validation import segmentation_validation, segmentation_validation_fr
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def get_args():
|
| 40 |
+
p = argparse.ArgumentParser()
|
| 41 |
+
p.add_argument('--dataset', required=True, choices=['modid', 'mhsi'])
|
| 42 |
+
p.add_argument('--encoder', default='mit_b0',
|
| 43 |
+
choices=list(ENCODER_SPECS.keys()))
|
| 44 |
+
p.add_argument('--opsin_mode', default='opsin_train', choices=list(OPSIN_MODES))
|
| 45 |
+
p.add_argument('--config', default='configs/modid.yaml')
|
| 46 |
+
p.add_argument('--workdir', default='work_dir/encoder_swap')
|
| 47 |
+
p.add_argument('--local_rank', default=os.getenv('LOCAL_RANK', 0), type=int)
|
| 48 |
+
p.add_argument('--backend', default='nccl')
|
| 49 |
+
p.add_argument('--seed', default=42, type=int)
|
| 50 |
+
p.add_argument('--pretrained_encoder', action='store_true')
|
| 51 |
+
return p.parse_args()
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def setup_logger(path):
|
| 55 |
+
fmt = logging.Formatter('%(asctime)s - %(levelname)s: %(message)s')
|
| 56 |
+
log = logging.getLogger()
|
| 57 |
+
log.setLevel(logging.INFO)
|
| 58 |
+
log.handlers.clear()
|
| 59 |
+
fh = logging.FileHandler(path, mode='w')
|
| 60 |
+
fh.setFormatter(fmt)
|
| 61 |
+
log.addHandler(fh)
|
| 62 |
+
sh = logging.StreamHandler()
|
| 63 |
+
sh.setFormatter(fmt)
|
| 64 |
+
log.addHandler(sh)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def cal_eta(t0, cur, total):
|
| 68 |
+
now = datetime.datetime.now().replace(microsecond=0)
|
| 69 |
+
scale = (total - cur) / float(cur)
|
| 70 |
+
eta = (now - t0) * scale
|
| 71 |
+
return str(now - t0), str(eta)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def build_dataloaders(dataset_name, local_rank):
|
| 75 |
+
nw = 4
|
| 76 |
+
if dataset_name == 'modid':
|
| 77 |
+
root = '/data/lyj/data/MODID'
|
| 78 |
+
shape = [270, 510]
|
| 79 |
+
train_ds = ModidDataset(root_dir=root, input_shape=shape, train=True)
|
| 80 |
+
val_ds = ModidDataset(root_dir=root, input_shape=shape, train=False)
|
| 81 |
+
train_sampler = DistributedSampler(train_ds)
|
| 82 |
+
train_loader = DataLoader(train_ds, batch_size=4, shuffle=False,
|
| 83 |
+
num_workers=nw, pin_memory=True, drop_last=True,
|
| 84 |
+
sampler=train_sampler, prefetch_factor=4)
|
| 85 |
+
val_loader = DataLoader(val_ds, batch_size=4, shuffle=False,
|
| 86 |
+
num_workers=nw, pin_memory=True, drop_last=False)
|
| 87 |
+
return train_loader, val_loader, train_sampler, 2
|
| 88 |
+
|
| 89 |
+
root = '/data/lyj/data/MHSI/'
|
| 90 |
+
with open(os.path.join(root, 'train_val_test.json')) as f:
|
| 91 |
+
split = json.load(f)
|
| 92 |
+
train_files = split['train'] + split['val']
|
| 93 |
+
test_files = split['test']
|
| 94 |
+
img_root = os.path.join(root, 'MHSI')
|
| 95 |
+
mask_root = os.path.join(root, 'Mask')
|
| 96 |
+
train_imgs = [os.path.join(img_root, x) for x in train_files]
|
| 97 |
+
train_masks = [os.path.join(mask_root, f'{x[:-4]}.png') for x in train_files]
|
| 98 |
+
test_imgs = [os.path.join(img_root, x) for x in test_files]
|
| 99 |
+
test_masks = [os.path.join(mask_root, f'{x[:-4]}.png') for x in test_files]
|
| 100 |
+
train_ds = Data_Generate_Bile(train_imgs, train_masks, transform=None,
|
| 101 |
+
principal_bands_num=-1, cutting=-1)
|
| 102 |
+
test_ds = Data_Generate_Bile(test_imgs, test_masks, transform=None,
|
| 103 |
+
principal_bands_num=-1, cutting=-1)
|
| 104 |
+
train_sampler = DistributedSampler(train_ds)
|
| 105 |
+
test_sampler = DistributedSampler(test_ds, shuffle=False)
|
| 106 |
+
train_loader = DataLoader(train_ds, sampler=train_sampler, batch_size=8,
|
| 107 |
+
num_workers=nw, drop_last=True)
|
| 108 |
+
val_loader = DataLoader(test_ds, sampler=test_sampler, batch_size=8,
|
| 109 |
+
shuffle=False, num_workers=nw, drop_last=False)
|
| 110 |
+
return train_loader, val_loader, train_sampler, 2
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def train(args, cfg):
|
| 114 |
+
torch.manual_seed(args.seed)
|
| 115 |
+
np.random.seed(args.seed)
|
| 116 |
+
random.seed(args.seed)
|
| 117 |
+
|
| 118 |
+
torch.cuda.set_device(args.local_rank)
|
| 119 |
+
dist.init_process_group(backend=args.backend,
|
| 120 |
+
timeout=datetime.timedelta(minutes=60))
|
| 121 |
+
device = torch.device('cuda', args.local_rank)
|
| 122 |
+
t0 = datetime.datetime.now().replace(microsecond=0)
|
| 123 |
+
|
| 124 |
+
train_loader, val_loader, train_sampler, num_classes = build_dataloaders(
|
| 125 |
+
args.dataset, args.local_rank)
|
| 126 |
+
|
| 127 |
+
evpl = build_evpl(args.dataset, args.opsin_mode, device)
|
| 128 |
+
evpl.to(device)
|
| 129 |
+
evpl = DistributedDataParallel(evpl, device_ids=[args.local_rank],
|
| 130 |
+
find_unused_parameters=True)
|
| 131 |
+
|
| 132 |
+
backbone = build_encoder(args.encoder, pretrained=args.pretrained_encoder)
|
| 133 |
+
backbone.to(device)
|
| 134 |
+
backbone = DistributedDataParallel(backbone, device_ids=[args.local_rank],
|
| 135 |
+
find_unused_parameters=True)
|
| 136 |
+
|
| 137 |
+
embed_dims = backbone.module.embed_dims
|
| 138 |
+
head = SegFormerHead(feature_strides=[4, 8, 16, 32],
|
| 139 |
+
in_channels=embed_dims,
|
| 140 |
+
embedding_dim=256,
|
| 141 |
+
num_classes=num_classes)
|
| 142 |
+
head.to(device)
|
| 143 |
+
head = DistributedDataParallel(head, device_ids=[args.local_rank],
|
| 144 |
+
find_unused_parameters=True)
|
| 145 |
+
|
| 146 |
+
criterion = torch.nn.CrossEntropyLoss(ignore_index=255).to(device)
|
| 147 |
+
bb_opt = torch.optim.Adam(backbone.parameters(), lr=6e-5)
|
| 148 |
+
hd_opt = torch.optim.SGD(head.parameters(), lr=5e-4, momentum=0.9, weight_decay=5e-4)
|
| 149 |
+
ev_opt = torch.optim.Adam(filter(lambda p: p.requires_grad, evpl.parameters()), lr=3e-2)
|
| 150 |
+
bb_sched = torch.optim.lr_scheduler.CosineAnnealingLR(bb_opt, T_max=cfg.train.num_epoch)
|
| 151 |
+
hd_sched = torch.optim.lr_scheduler.CosineAnnealingLR(hd_opt, T_max=cfg.train.num_epoch)
|
| 152 |
+
ev_sched = torch.optim.lr_scheduler.CosineAnnealingLR(ev_opt, T_max=cfg.train.num_epoch)
|
| 153 |
+
|
| 154 |
+
validate_fn = (segmentation_validation_fr if args.dataset == 'modid'
|
| 155 |
+
else segmentation_validation)
|
| 156 |
+
best_miou = 0.0
|
| 157 |
+
|
| 158 |
+
for epoch in range(cfg.train.num_epoch):
|
| 159 |
+
backbone.train()
|
| 160 |
+
head.train()
|
| 161 |
+
evpl.train()
|
| 162 |
+
train_sampler.set_epoch(epoch)
|
| 163 |
+
for step, data in enumerate(train_loader):
|
| 164 |
+
hsi, label = data
|
| 165 |
+
hsi = hsi.to(device, non_blocking=True)
|
| 166 |
+
if args.dataset == 'modid':
|
| 167 |
+
label = label.to(device, non_blocking=True)
|
| 168 |
+
else:
|
| 169 |
+
label = label.squeeze(1).type(torch.uint8).to(device, non_blocking=True)
|
| 170 |
+
|
| 171 |
+
feat = backbone(evpl(hsi))
|
| 172 |
+
out = head(feat)
|
| 173 |
+
out = F.interpolate(out, size=label.shape[1:], mode='bilinear', align_corners=False)
|
| 174 |
+
loss = criterion(out, label.long())
|
| 175 |
+
|
| 176 |
+
bb_opt.zero_grad()
|
| 177 |
+
hd_opt.zero_grad()
|
| 178 |
+
ev_opt.zero_grad()
|
| 179 |
+
loss.backward()
|
| 180 |
+
bb_opt.step()
|
| 181 |
+
hd_opt.step()
|
| 182 |
+
ev_opt.step()
|
| 183 |
+
|
| 184 |
+
if args.local_rank == 0 and step == 0:
|
| 185 |
+
d, eta = cal_eta(t0, epoch + 1, cfg.train.num_epoch)
|
| 186 |
+
logging.info('Epoch %d/%d loss=%.4f elapsed=%s eta=%s',
|
| 187 |
+
epoch + 1, cfg.train.num_epoch, loss.item(), d, eta)
|
| 188 |
+
|
| 189 |
+
bb_sched.step()
|
| 190 |
+
hd_sched.step()
|
| 191 |
+
ev_sched.step()
|
| 192 |
+
|
| 193 |
+
if (epoch + 1) % cfg.train.eval_epoch == 0:
|
| 194 |
+
metrics = validate_fn(backbone=backbone, seg_decoder=head,
|
| 195 |
+
EVPL_model=evpl, criterion=criterion,
|
| 196 |
+
data_loader=val_loader, num_classes=num_classes)
|
| 197 |
+
if args.local_rank == 0:
|
| 198 |
+
logging.info('Epoch %d validate: %s', epoch + 1, metrics)
|
| 199 |
+
miou = float(metrics.get('Mean IoU', 0))
|
| 200 |
+
if miou > best_miou:
|
| 201 |
+
best_miou = miou
|
| 202 |
+
torch.save({
|
| 203 |
+
'encoder': args.encoder,
|
| 204 |
+
'opsin_mode': args.opsin_mode,
|
| 205 |
+
'dataset': args.dataset,
|
| 206 |
+
'best_miou': best_miou,
|
| 207 |
+
'epoch': epoch + 1,
|
| 208 |
+
'backbone': backbone.module.state_dict(),
|
| 209 |
+
'head': head.module.state_dict(),
|
| 210 |
+
'evpl': evpl.module.state_dict(),
|
| 211 |
+
}, os.path.join(args.workdir, 'best.pth'))
|
| 212 |
+
logging.info('New best mIoU=%.4f at epoch %d', best_miou, epoch + 1)
|
| 213 |
+
|
| 214 |
+
if args.local_rank == 0:
|
| 215 |
+
with open(os.path.join(args.workdir, 'result.json'), 'w') as f:
|
| 216 |
+
json.dump({
|
| 217 |
+
'dataset': args.dataset,
|
| 218 |
+
'encoder': args.encoder,
|
| 219 |
+
'opsin_mode': args.opsin_mode,
|
| 220 |
+
'best_miou': best_miou,
|
| 221 |
+
'num_epoch': cfg.train.num_epoch,
|
| 222 |
+
}, f, indent=2)
|
| 223 |
+
logging.info('Done. best mIoU=%.4f', best_miou)
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
if __name__ == '__main__':
|
| 227 |
+
args = get_args()
|
| 228 |
+
cfg = OmegaConf.load(args.config)
|
| 229 |
+
os.makedirs(args.workdir, exist_ok=True)
|
| 230 |
+
tag = f'{args.dataset}_{args.encoder}_{args.opsin_mode}'
|
| 231 |
+
log_path = os.path.join(args.workdir, f'{tag}.log')
|
| 232 |
+
if args.local_rank == 0:
|
| 233 |
+
setup_logger(log_path)
|
| 234 |
+
logging.info('Experiment: dataset=%s encoder=%s opsin=%s',
|
| 235 |
+
args.dataset, args.encoder, args.opsin_mode)
|
| 236 |
+
logging.info('Post-SegFormer encoders: %s', POST_SEGFORMER_ENCODERS)
|
| 237 |
+
logging.info('Config: %s', cfg)
|
| 238 |
+
train(args, cfg)
|
lib_hsi_exp_v2.py
ADDED
|
@@ -0,0 +1,379 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import datetime
|
| 4 |
+
import argparse
|
| 5 |
+
import logging
|
| 6 |
+
import random
|
| 7 |
+
import numpy as np
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
import torch.distributed as dist
|
| 11 |
+
import torch.nn.functional as F
|
| 12 |
+
from dataloader.lib_hsi import LIBHSIDataset
|
| 13 |
+
from models.backbone.mix_transformer import mit_b0, mit_b3, mit_b5, mit_b1
|
| 14 |
+
from models.HSI_to_RGB.lib_hsi_EVPL import EVPL
|
| 15 |
+
from models.decoder.segformer_head import SegFormerHead
|
| 16 |
+
from util.validation import seg_validate_for_HSI2, segmentation_validation
|
| 17 |
+
from omegaconf import OmegaConf
|
| 18 |
+
from torch.nn.parallel import DistributedDataParallel
|
| 19 |
+
from torch.utils.data import DataLoader
|
| 20 |
+
from torch.utils.data.distributed import DistributedSampler
|
| 21 |
+
from util import eval_seg
|
| 22 |
+
|
| 23 |
+
class FocalLoss(nn.Module):
|
| 24 |
+
|
| 25 |
+
def __init__(self, alpha=None, gamma=2.0, ignore_index=255, reduction='mean', label_smoothing=0.0):
|
| 26 |
+
super(FocalLoss, self).__init__()
|
| 27 |
+
self.gamma = gamma
|
| 28 |
+
self.alpha = alpha
|
| 29 |
+
self.ignore_index = ignore_index
|
| 30 |
+
self.reduction = reduction
|
| 31 |
+
self.label_smoothing = label_smoothing
|
| 32 |
+
|
| 33 |
+
def forward(self, inputs, targets):
|
| 34 |
+
ce_loss = F.cross_entropy(inputs, targets, reduction='none', ignore_index=self.ignore_index, label_smoothing=self.label_smoothing)
|
| 35 |
+
pt = torch.exp(-ce_loss)
|
| 36 |
+
focal_loss = (1 - pt) ** self.gamma * ce_loss
|
| 37 |
+
if self.alpha is not None:
|
| 38 |
+
alpha = self.alpha.to(inputs.device)
|
| 39 |
+
valid_mask = targets != self.ignore_index
|
| 40 |
+
targets_clamped = targets.clone()
|
| 41 |
+
targets_clamped[~valid_mask] = 0
|
| 42 |
+
alpha_t = alpha.gather(0, targets_clamped.flatten())
|
| 43 |
+
alpha_t = alpha_t.view(targets.shape)
|
| 44 |
+
alpha_t[~valid_mask] = 0
|
| 45 |
+
focal_loss = alpha_t * focal_loss
|
| 46 |
+
if self.reduction == 'mean':
|
| 47 |
+
return focal_loss.mean()
|
| 48 |
+
elif self.reduction == 'sum':
|
| 49 |
+
return focal_loss.sum()
|
| 50 |
+
return focal_loss
|
| 51 |
+
|
| 52 |
+
class DiceLoss(nn.Module):
|
| 53 |
+
|
| 54 |
+
def __init__(self, num_classes, ignore_index=255, smooth=1.0):
|
| 55 |
+
super(DiceLoss, self).__init__()
|
| 56 |
+
self.num_classes = num_classes
|
| 57 |
+
self.ignore_index = ignore_index
|
| 58 |
+
self.smooth = smooth
|
| 59 |
+
|
| 60 |
+
def forward(self, inputs, targets):
|
| 61 |
+
probs = F.softmax(inputs, dim=1)
|
| 62 |
+
targets_one_hot = torch.zeros_like(probs)
|
| 63 |
+
valid_mask = (targets != self.ignore_index).unsqueeze(1).expand_as(targets_one_hot)
|
| 64 |
+
targets_clamped = targets.clone()
|
| 65 |
+
targets_clamped[targets == self.ignore_index] = 0
|
| 66 |
+
targets_one_hot.scatter_(1, targets_clamped.unsqueeze(1), 1)
|
| 67 |
+
targets_one_hot = targets_one_hot * valid_mask.float()
|
| 68 |
+
dims = (0, 2, 3)
|
| 69 |
+
intersection = torch.sum(probs * targets_one_hot, dims)
|
| 70 |
+
cardinality = torch.sum(probs + targets_one_hot, dims)
|
| 71 |
+
dice = (2.0 * intersection + self.smooth) / (cardinality + self.smooth)
|
| 72 |
+
return 1.0 - dice.mean()
|
| 73 |
+
|
| 74 |
+
def get_args_parser():
|
| 75 |
+
parser = argparse.ArgumentParser(description='LIB-HSI Semantic Segmentation Training (Improved)')
|
| 76 |
+
parser.add_argument('--config', default='configs/lib_hsi.yaml', type=str)
|
| 77 |
+
parser.add_argument('--local_rank', default=os.getenv('LOCAL_RANK', 0), type=int)
|
| 78 |
+
parser.add_argument('--backend', default='nccl')
|
| 79 |
+
parser.add_argument('--workdir', type=str, default='work_dir/lib_hsi_v2')
|
| 80 |
+
parser.add_argument('--backbone_pretrain', default=None)
|
| 81 |
+
parser.add_argument('--head_pretrain', default=None)
|
| 82 |
+
parser.add_argument('--evpl_pretrain', default=None)
|
| 83 |
+
parser.add_argument('--encoder_type', default='mit_b1', type=str, choices=['mit_b0', 'mit_b1', 'mit_b3', 'mit_b5'])
|
| 84 |
+
parser.add_argument('--seed', default=42, type=int)
|
| 85 |
+
parser.add_argument('--num_classes', default=44, type=int)
|
| 86 |
+
parser.add_argument('--batch_size', default=16, type=int, help=' batch size (16) ')
|
| 87 |
+
parser.add_argument('--input_size', default=256, type=int)
|
| 88 |
+
parser.add_argument('--loss_type', default='focal', type=str, choices=['ce', 'focal', 'ce_dice'], help='')
|
| 89 |
+
parser.add_argument('--focal_gamma', default=2.0, type=float)
|
| 90 |
+
parser.add_argument('--use_class_weight', action='store_true', default=True, help='')
|
| 91 |
+
parser.add_argument('--backbone_lr', default=0.0001, type=float, help='backbone ( head )')
|
| 92 |
+
parser.add_argument('--head_lr', default=0.0005, type=float)
|
| 93 |
+
parser.add_argument('--evpl_lr', default=0.0001, type=float)
|
| 94 |
+
parser.add_argument('--weight_decay', default=0.01, type=float)
|
| 95 |
+
parser.add_argument('--warmup_epochs', default=10, type=int)
|
| 96 |
+
parser.add_argument('--grad_clip', default=1.0, type=float, help='')
|
| 97 |
+
parser.add_argument('--use_mixup', action='store_true', default=False)
|
| 98 |
+
parser.add_argument('--mixup_alpha', default=0.2, type=float)
|
| 99 |
+
parser.add_argument('--freeze_evpl', action='store_true', default=False, help=' EVPL ')
|
| 100 |
+
parser.add_argument('--label_smoothing', default=0.1, type=float, help='Label smoothing factor (0.0-0.2 recommended)')
|
| 101 |
+
if 'LOCAL_RANK' not in os.environ:
|
| 102 |
+
os.environ['LOCAL_RANK'] = os.environ.get('SLURM_PROCID', '0')
|
| 103 |
+
return parser
|
| 104 |
+
|
| 105 |
+
def setup_seed(seed):
|
| 106 |
+
torch.manual_seed(seed)
|
| 107 |
+
torch.cuda.manual_seed_all(seed)
|
| 108 |
+
np.random.seed(seed)
|
| 109 |
+
random.seed(seed)
|
| 110 |
+
torch.backends.cudnn.deterministic = True
|
| 111 |
+
|
| 112 |
+
def setup_logger(filename):
|
| 113 |
+
logFormatter = logging.Formatter('%(asctime)s - %(filename)s - %(levelname)s: %(message)s')
|
| 114 |
+
logger = logging.getLogger()
|
| 115 |
+
logger.setLevel(logging.INFO)
|
| 116 |
+
fHandler = logging.FileHandler(filename, mode='w')
|
| 117 |
+
fHandler.setFormatter(logFormatter)
|
| 118 |
+
logger.addHandler(fHandler)
|
| 119 |
+
cHandler = logging.StreamHandler()
|
| 120 |
+
cHandler.setFormatter(logFormatter)
|
| 121 |
+
logger.addHandler(cHandler)
|
| 122 |
+
|
| 123 |
+
def cal_eta(time0, cur_iter, total_iter):
|
| 124 |
+
time_now = datetime.datetime.now().replace(microsecond=0)
|
| 125 |
+
scale = (total_iter - cur_iter) / float(cur_iter + 1e-06)
|
| 126 |
+
delta = time_now - time0
|
| 127 |
+
eta = delta * scale
|
| 128 |
+
time_fin = time_now + eta
|
| 129 |
+
eta = time_fin.replace(microsecond=0) - time_now
|
| 130 |
+
return (str(delta), str(eta))
|
| 131 |
+
|
| 132 |
+
def compute_class_weights(dataset, num_classes, device, max_weight=10.0):
|
| 133 |
+
logging.info('Computing class weights from dataset...')
|
| 134 |
+
class_counts = torch.zeros(num_classes, dtype=torch.float64)
|
| 135 |
+
sample_size = min(100, len(dataset))
|
| 136 |
+
indices = random.sample(range(len(dataset)), sample_size)
|
| 137 |
+
for idx in indices:
|
| 138 |
+
(_, label) = dataset[idx]
|
| 139 |
+
label = label.numpy().flatten()
|
| 140 |
+
label = label[label < num_classes]
|
| 141 |
+
for c in label:
|
| 142 |
+
class_counts[c] += 1
|
| 143 |
+
total = class_counts.sum()
|
| 144 |
+
weights = total / (class_counts + 1e-06)
|
| 145 |
+
weights = weights / weights.mean()
|
| 146 |
+
weights = torch.clamp(weights, 0.1, max_weight)
|
| 147 |
+
weights[class_counts == 0] = 1.0
|
| 148 |
+
logging.info(f'Class weights computed. Min={weights.min():.2f}, Max={weights.max():.2f}')
|
| 149 |
+
logging.info(f'Non-zero classes: {(class_counts > 0).sum().item()}/{num_classes}')
|
| 150 |
+
return weights.float().to(device)
|
| 151 |
+
|
| 152 |
+
def mixup_data(x, y, alpha=0.2):
|
| 153 |
+
if alpha > 0:
|
| 154 |
+
lam = np.random.beta(alpha, alpha)
|
| 155 |
+
else:
|
| 156 |
+
lam = 1
|
| 157 |
+
batch_size = x.size(0)
|
| 158 |
+
index = torch.randperm(batch_size).to(x.device)
|
| 159 |
+
mixed_x = lam * x + (1 - lam) * x[index, :]
|
| 160 |
+
(y_a, y_b) = (y, y[index])
|
| 161 |
+
return (mixed_x, y_a, y_b, lam)
|
| 162 |
+
|
| 163 |
+
def mixup_criterion(criterion, pred, y_a, y_b, lam):
|
| 164 |
+
return lam * criterion(pred, y_a) + (1 - lam) * criterion(pred, y_b)
|
| 165 |
+
|
| 166 |
+
class WarmupCosineScheduler:
|
| 167 |
+
|
| 168 |
+
def __init__(self, optimizer, warmup_epochs, total_epochs, base_lr, min_lr=1e-06):
|
| 169 |
+
self.optimizer = optimizer
|
| 170 |
+
self.warmup_epochs = warmup_epochs
|
| 171 |
+
self.total_epochs = total_epochs
|
| 172 |
+
self.base_lr = base_lr
|
| 173 |
+
self.min_lr = min_lr
|
| 174 |
+
self.current_epoch = 0
|
| 175 |
+
|
| 176 |
+
def step(self):
|
| 177 |
+
self.current_epoch += 1
|
| 178 |
+
if self.current_epoch <= self.warmup_epochs:
|
| 179 |
+
lr = self.base_lr * self.current_epoch / self.warmup_epochs
|
| 180 |
+
else:
|
| 181 |
+
progress = (self.current_epoch - self.warmup_epochs) / (self.total_epochs - self.warmup_epochs)
|
| 182 |
+
lr = self.min_lr + 0.5 * (self.base_lr - self.min_lr) * (1 + np.cos(np.pi * progress))
|
| 183 |
+
for param_group in self.optimizer.param_groups:
|
| 184 |
+
param_group['lr'] = lr
|
| 185 |
+
return lr
|
| 186 |
+
|
| 187 |
+
def train(cfg, args):
|
| 188 |
+
setup_seed(args.seed)
|
| 189 |
+
num_workers = 4
|
| 190 |
+
torch.cuda.set_device(args.local_rank)
|
| 191 |
+
dist.init_process_group(backend=args.backend, timeout=datetime.timedelta(minutes=50))
|
| 192 |
+
time0 = datetime.datetime.now().replace(microsecond=0)
|
| 193 |
+
device = torch.device('cuda')
|
| 194 |
+
num_classes = args.num_classes
|
| 195 |
+
train_path = 'datasets/LIB-HSI'
|
| 196 |
+
val_path = 'datasets/LIB-HSI'
|
| 197 |
+
HSI_input_shape = [args.input_size, args.input_size]
|
| 198 |
+
HSI_train_dataset = LIBHSIDataset(root_dir=train_path, input_shape=HSI_input_shape, train=True, num_classes=num_classes)
|
| 199 |
+
HSI_val_dataset = LIBHSIDataset(root_dir=val_path, input_shape=HSI_input_shape, train=False, num_classes=num_classes)
|
| 200 |
+
HSI_train_sampler = DistributedSampler(HSI_train_dataset)
|
| 201 |
+
HSI_train_loader = DataLoader(HSI_train_dataset, batch_size=args.batch_size, num_workers=num_workers, pin_memory=True, drop_last=True, sampler=HSI_train_sampler, prefetch_factor=4)
|
| 202 |
+
HSI_val_loader = DataLoader(HSI_val_dataset, batch_size=args.batch_size, shuffle=False, num_workers=num_workers, pin_memory=True, drop_last=False)
|
| 203 |
+
if args.local_rank == 0:
|
| 204 |
+
logging.info(f'{torch.cuda.device_count()} GPUs are available')
|
| 205 |
+
(wavelength_1, wavelength_2, wavelength_3) = (450.0, 530.0, 580.0)
|
| 206 |
+
EVPL_model = EVPL(lamda_max_1=wavelength_1, lamda_max_2=wavelength_2, lamda_max_3=wavelength_3, device=device, use_isp=False)
|
| 207 |
+
if args.evpl_pretrain is not None:
|
| 208 |
+
EVPL_model_dict = EVPL_model.state_dict()
|
| 209 |
+
EVPL_pre_train_dict = torch.load(args.evpl_pretrain, map_location=device)
|
| 210 |
+
EVPL_model_dict.update(EVPL_pre_train_dict)
|
| 211 |
+
EVPL_model.load_state_dict(EVPL_model_dict)
|
| 212 |
+
logging.info(f'Loaded EVPL pretrain from {args.evpl_pretrain}')
|
| 213 |
+
if args.freeze_evpl:
|
| 214 |
+
for param in EVPL_model.parameters():
|
| 215 |
+
param.requires_grad = False
|
| 216 |
+
logging.info('EVPL parameters frozen')
|
| 217 |
+
EVPL_model.to(device)
|
| 218 |
+
EVPL_model = DistributedDataParallel(EVPL_model, device_ids=[args.local_rank], find_unused_parameters=True)
|
| 219 |
+
if args.encoder_type == 'mit_b0':
|
| 220 |
+
backbone = mit_b0()
|
| 221 |
+
elif args.encoder_type == 'mit_b1':
|
| 222 |
+
backbone = mit_b1()
|
| 223 |
+
elif args.encoder_type == 'mit_b3':
|
| 224 |
+
backbone = mit_b3()
|
| 225 |
+
elif args.encoder_type == 'mit_b5':
|
| 226 |
+
backbone = mit_b5()
|
| 227 |
+
if args.backbone_pretrain is not None:
|
| 228 |
+
backbone_dict = backbone.state_dict()
|
| 229 |
+
backbone_pre_train_dict = torch.load(args.backbone_pretrain, map_location=device)
|
| 230 |
+
backbone_dict.update(backbone_pre_train_dict)
|
| 231 |
+
backbone.load_state_dict(backbone_dict)
|
| 232 |
+
logging.info(f'Loaded backbone pretrain from {args.backbone_pretrain}')
|
| 233 |
+
backbone.to(device)
|
| 234 |
+
backbone = DistributedDataParallel(backbone, device_ids=[args.local_rank], find_unused_parameters=True)
|
| 235 |
+
seg_decoder = SegFormerHead(feature_strides=[4, 8, 16, 32], in_channels=backbone.module.embed_dims, embedding_dim=256, num_classes=num_classes)
|
| 236 |
+
if args.head_pretrain is not None:
|
| 237 |
+
seg_decoder_dict = seg_decoder.state_dict()
|
| 238 |
+
seg_decoder_pre_train_dict = torch.load(args.head_pretrain, map_location=device)
|
| 239 |
+
seg_decoder_dict.update(seg_decoder_pre_train_dict)
|
| 240 |
+
seg_decoder.load_state_dict(seg_decoder_dict)
|
| 241 |
+
logging.info(f'Loaded decoder pretrain from {args.head_pretrain}')
|
| 242 |
+
seg_decoder.to(device)
|
| 243 |
+
seg_decoder = DistributedDataParallel(seg_decoder, device_ids=[args.local_rank], find_unused_parameters=True)
|
| 244 |
+
class_weights = None
|
| 245 |
+
if args.use_class_weight and args.local_rank == 0:
|
| 246 |
+
class_weights = compute_class_weights(HSI_train_dataset, num_classes, device)
|
| 247 |
+
if args.use_class_weight:
|
| 248 |
+
if args.local_rank != 0:
|
| 249 |
+
class_weights = torch.zeros(num_classes, device=device)
|
| 250 |
+
dist.broadcast(class_weights, src=0)
|
| 251 |
+
if args.loss_type == 'focal':
|
| 252 |
+
criterion = FocalLoss(alpha=class_weights, gamma=args.focal_gamma, ignore_index=255, label_smoothing=args.label_smoothing)
|
| 253 |
+
logging.info(f'Using Focal Loss with gamma={args.focal_gamma}, label_smoothing={args.label_smoothing}')
|
| 254 |
+
elif args.loss_type == 'ce_dice':
|
| 255 |
+
ce_criterion = nn.CrossEntropyLoss(weight=class_weights, ignore_index=255, label_smoothing=args.label_smoothing)
|
| 256 |
+
dice_criterion = DiceLoss(num_classes=num_classes, ignore_index=255)
|
| 257 |
+
criterion = lambda pred, target: ce_criterion(pred, target) + dice_criterion(pred, target)
|
| 258 |
+
logging.info(f'Using CE + Dice Loss with label_smoothing={args.label_smoothing}')
|
| 259 |
+
else:
|
| 260 |
+
criterion = nn.CrossEntropyLoss(weight=class_weights, ignore_index=255, label_smoothing=args.label_smoothing)
|
| 261 |
+
logging.info(f'Using CrossEntropy Loss with label_smoothing={args.label_smoothing}')
|
| 262 |
+
backbone_optimizer = torch.optim.AdamW(backbone.parameters(), lr=args.backbone_lr, weight_decay=args.weight_decay)
|
| 263 |
+
head_optimizer = torch.optim.AdamW(seg_decoder.parameters(), lr=args.head_lr, weight_decay=args.weight_decay)
|
| 264 |
+
evpl_optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, EVPL_model.parameters()), lr=args.evpl_lr)
|
| 265 |
+
total_epochs = cfg.train.num_epoch
|
| 266 |
+
backbone_scheduler = WarmupCosineScheduler(backbone_optimizer, args.warmup_epochs, total_epochs, args.backbone_lr)
|
| 267 |
+
head_scheduler = WarmupCosineScheduler(head_optimizer, args.warmup_epochs, total_epochs, args.head_lr)
|
| 268 |
+
evpl_scheduler = WarmupCosineScheduler(evpl_optimizer, args.warmup_epochs, total_epochs, args.evpl_lr)
|
| 269 |
+
if args.local_rank == 0:
|
| 270 |
+
logging.info('=' * 60)
|
| 271 |
+
logging.info('Training Configuration:')
|
| 272 |
+
logging.info(f' Backbone: {args.encoder_type}')
|
| 273 |
+
logging.info(f' Loss: {args.loss_type}')
|
| 274 |
+
logging.info(f' Batch size: {args.batch_size}')
|
| 275 |
+
logging.info(f' Input size: {args.input_size}')
|
| 276 |
+
logging.info(f' Backbone LR: {args.backbone_lr}')
|
| 277 |
+
logging.info(f' Head LR: {args.head_lr}')
|
| 278 |
+
logging.info(f' EVPL LR: {args.evpl_lr}')
|
| 279 |
+
logging.info(f' Warmup epochs: {args.warmup_epochs}')
|
| 280 |
+
logging.info(f' Class weights: {args.use_class_weight}')
|
| 281 |
+
logging.info(f' Freeze EVPL: {args.freeze_evpl}')
|
| 282 |
+
logging.info('=' * 60)
|
| 283 |
+
best_miou = 0.0
|
| 284 |
+
for epoch in range(total_epochs):
|
| 285 |
+
HSI_train_sampler.set_epoch(epoch)
|
| 286 |
+
(preds, gts) = ([], [])
|
| 287 |
+
epoch_loss = 0.0
|
| 288 |
+
num_batches = 0
|
| 289 |
+
for (step, data) in enumerate(HSI_train_loader):
|
| 290 |
+
backbone.train()
|
| 291 |
+
seg_decoder.train()
|
| 292 |
+
EVPL_model.train()
|
| 293 |
+
(hsi, label) = data
|
| 294 |
+
print('hsi', hsi.shape)
|
| 295 |
+
hsi = hsi.to(device, non_blocking=True)
|
| 296 |
+
label = label.to(device, non_blocking=True)
|
| 297 |
+
if args.use_mixup:
|
| 298 |
+
(hsi, label_a, label_b, lam) = mixup_data(hsi, label, args.mixup_alpha)
|
| 299 |
+
rgb_features = EVPL_model(hsi)
|
| 300 |
+
features = backbone(rgb_features)
|
| 301 |
+
seg_outputs = seg_decoder(features)
|
| 302 |
+
seg_outputs = F.interpolate(seg_outputs, size=label.shape[1:], mode='bilinear', align_corners=False)
|
| 303 |
+
if args.use_mixup:
|
| 304 |
+
seg_loss = mixup_criterion(criterion, seg_outputs, label_a.long(), label_b.long(), lam)
|
| 305 |
+
else:
|
| 306 |
+
seg_loss = criterion(seg_outputs, label.long())
|
| 307 |
+
preds += list(torch.argmax(seg_outputs.detach(), dim=1).cpu().numpy().astype(np.int16))
|
| 308 |
+
gts += list(label.detach().cpu().numpy().astype(np.int16))
|
| 309 |
+
backbone_optimizer.zero_grad()
|
| 310 |
+
head_optimizer.zero_grad()
|
| 311 |
+
evpl_optimizer.zero_grad()
|
| 312 |
+
seg_loss.backward()
|
| 313 |
+
if args.grad_clip > 0:
|
| 314 |
+
torch.nn.utils.clip_grad_norm_(backbone.parameters(), args.grad_clip)
|
| 315 |
+
torch.nn.utils.clip_grad_norm_(seg_decoder.parameters(), args.grad_clip)
|
| 316 |
+
torch.nn.utils.clip_grad_norm_(EVPL_model.parameters(), args.grad_clip)
|
| 317 |
+
backbone_optimizer.step()
|
| 318 |
+
head_optimizer.step()
|
| 319 |
+
evpl_optimizer.step()
|
| 320 |
+
epoch_loss += seg_loss.item()
|
| 321 |
+
num_batches += 1
|
| 322 |
+
backbone_lr = backbone_scheduler.step()
|
| 323 |
+
head_scheduler.step()
|
| 324 |
+
evpl_scheduler.step()
|
| 325 |
+
score = eval_seg.scores(gts, preds, num_classes=num_classes)
|
| 326 |
+
avg_loss = epoch_loss / num_batches
|
| 327 |
+
if args.local_rank == 0:
|
| 328 |
+
(delta, eta) = cal_eta(time0, epoch + 1, total_epochs)
|
| 329 |
+
logging.info(f"Epoch: {epoch + 1}/{total_epochs}; Loss: {avg_loss:.4f}; Train mIoU: {score['Mean IoU']:.4f}; Elapsed: {delta}; ETA: {eta}")
|
| 330 |
+
if not args.freeze_evpl:
|
| 331 |
+
lambda_info = EVPL_model.module.get_lambda_max()
|
| 332 |
+
logging.info(f" Lambda: λ1={lambda_info['lambda_1']:.2f}nm, λ2={lambda_info['lambda_2']:.2f}nm, λ3={lambda_info['lambda_3']:.2f}nm (std={lambda_info['std']:.1f}nm fixed)")
|
| 333 |
+
logging.info(f' LR: backbone={backbone_lr:.2e}, head={head_scheduler.current_epoch}')
|
| 334 |
+
if (epoch + 1) % cfg.train.eval_epoch == 0:
|
| 335 |
+
backbone.eval()
|
| 336 |
+
seg_decoder.eval()
|
| 337 |
+
EVPL_model.eval()
|
| 338 |
+
(val_preds, val_gts) = ([], [])
|
| 339 |
+
val_loss_total = 0.0
|
| 340 |
+
with torch.no_grad():
|
| 341 |
+
for data in HSI_val_loader:
|
| 342 |
+
(hsi, label) = data
|
| 343 |
+
hsi = hsi.to(device, non_blocking=True)
|
| 344 |
+
label = label.to(device, non_blocking=True)
|
| 345 |
+
rgb_features = EVPL_model(hsi)
|
| 346 |
+
features = backbone(rgb_features)
|
| 347 |
+
seg_outputs = seg_decoder(features)
|
| 348 |
+
seg_outputs = F.interpolate(seg_outputs, size=label.shape[1:], mode='bilinear', align_corners=False)
|
| 349 |
+
val_loss = criterion(seg_outputs, label.long())
|
| 350 |
+
val_loss_total += val_loss.item()
|
| 351 |
+
val_preds += list(torch.argmax(seg_outputs, dim=1).cpu().numpy().astype(np.int16))
|
| 352 |
+
val_gts += list(label.cpu().numpy().astype(np.int16))
|
| 353 |
+
val_score = eval_seg.scores(val_gts, val_preds, num_classes=num_classes)
|
| 354 |
+
val_miou = val_score['Mean IoU']
|
| 355 |
+
if args.local_rank == 0:
|
| 356 |
+
logging.info(f"Validation: Loss={val_loss_total / len(HSI_val_loader):.4f}, mIoU={val_miou:.4f}, PA={val_score['Pixel Accuracy']:.4f}")
|
| 357 |
+
if val_miou > best_miou:
|
| 358 |
+
best_miou = val_miou
|
| 359 |
+
torch.save(backbone.module.state_dict(), os.path.join(args.workdir, 'best_backbone.pth'))
|
| 360 |
+
torch.save(seg_decoder.module.state_dict(), os.path.join(args.workdir, 'best_head.pth'))
|
| 361 |
+
torch.save(EVPL_model.module.state_dict(), os.path.join(args.workdir, 'best_evpl.pth'))
|
| 362 |
+
logging.info(f'Best model saved! mIoU: {best_miou:.4f}')
|
| 363 |
+
if args.local_rank == 0 and (epoch + 1) % 50 == 0:
|
| 364 |
+
torch.save({'epoch': epoch + 1, 'backbone': backbone.module.state_dict(), 'head': seg_decoder.module.state_dict(), 'evpl': EVPL_model.module.state_dict(), 'backbone_optimizer': backbone_optimizer.state_dict(), 'head_optimizer': head_optimizer.state_dict(), 'evpl_optimizer': evpl_optimizer.state_dict(), 'best_miou': best_miou}, os.path.join(args.workdir, f'checkpoint_epoch{epoch + 1}.pth'))
|
| 365 |
+
if args.local_rank == 0:
|
| 366 |
+
logging.info(f'Training finished! Best validation mIoU: {best_miou:.4f}')
|
| 367 |
+
if __name__ == '__main__':
|
| 368 |
+
args = get_args_parser().parse_args()
|
| 369 |
+
cfg = OmegaConf.load(args.config)
|
| 370 |
+
if args.local_rank == 0:
|
| 371 |
+
logging.info(f'\nConfigs: {cfg}')
|
| 372 |
+
logging.info(f'Arguments: {args}')
|
| 373 |
+
if not os.path.exists(args.workdir):
|
| 374 |
+
os.makedirs(args.workdir, exist_ok=True)
|
| 375 |
+
setup_logger(os.path.join(args.workdir, 'lib_hsi_train_v2.log'))
|
| 376 |
+
if args.local_rank == 0:
|
| 377 |
+
logging.info(f'\nConfigs: {cfg}')
|
| 378 |
+
logging.info(f'Arguments: {args}')
|
| 379 |
+
train(cfg, args)
|
mars_exp.py
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import datetime
|
| 4 |
+
import argparse
|
| 5 |
+
import logging
|
| 6 |
+
import random
|
| 7 |
+
import numpy as np
|
| 8 |
+
import torch
|
| 9 |
+
import torch.distributed as dist
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
from dataloader.Mars import MarsDataset
|
| 12 |
+
from models.backbone.mix_transformer import mit_b0, mit_b3, mit_b5, mit_b1
|
| 13 |
+
from models.HSI_to_RGB.Mars3 import EVPL
|
| 14 |
+
from models.decoder.segformer_head import SegFormerHead
|
| 15 |
+
from util.validation import segmentation_validation
|
| 16 |
+
from omegaconf import OmegaConf
|
| 17 |
+
from torch.nn.parallel import DistributedDataParallel
|
| 18 |
+
from torch.utils.data import DataLoader
|
| 19 |
+
from torch.utils.data.distributed import DistributedSampler
|
| 20 |
+
|
| 21 |
+
def get_args_parser():
|
| 22 |
+
parser = argparse.ArgumentParser()
|
| 23 |
+
parser.add_argument('--config', default='configs/mars.yaml', type=str)
|
| 24 |
+
parser.add_argument('--local_rank', default=int(os.getenv('LOCAL_RANK', 0)), type=int)
|
| 25 |
+
parser.add_argument('--backend', default='nccl')
|
| 26 |
+
parser.add_argument('--workdir', type=str, default='work_dir/mars')
|
| 27 |
+
parser.add_argument('--train_path', type=str, default='datasets/Mars/MSL/train')
|
| 28 |
+
parser.add_argument('--val_path', type=str, default='datasets/Mars/MSL/test')
|
| 29 |
+
parser.add_argument('--batch_size', type=int, default=None)
|
| 30 |
+
parser.add_argument('--input_size', type=int, default=512)
|
| 31 |
+
parser.add_argument('--num_workers', type=int, default=4)
|
| 32 |
+
parser.add_argument('--max_steps', type=int, default=None)
|
| 33 |
+
parser.add_argument('--skip_val', action='store_true')
|
| 34 |
+
parser.add_argument('--backbone_pretrain', default=None)
|
| 35 |
+
parser.add_argument('--head_pretrain', default=None)
|
| 36 |
+
parser.add_argument('--evpl_pretrain', default=None)
|
| 37 |
+
parser.add_argument('--encoder_type', default='mit_b0', type=str, choices=['mit_b0', 'mit_b1', 'mit_b3', 'mit_b5'])
|
| 38 |
+
parser.add_argument('--seed', default=42, type=int)
|
| 39 |
+
if 'LOCAL_RANK' not in os.environ:
|
| 40 |
+
os.environ['LOCAL_RANK'] = '0'
|
| 41 |
+
return parser
|
| 42 |
+
|
| 43 |
+
def setup_seed(seed):
|
| 44 |
+
torch.manual_seed(seed)
|
| 45 |
+
torch.cuda.manual_seed_all(seed)
|
| 46 |
+
np.random.seed(seed)
|
| 47 |
+
random.seed(seed)
|
| 48 |
+
torch.backends.cudnn.deterministic = True
|
| 49 |
+
|
| 50 |
+
def setup_logger(filename):
|
| 51 |
+
logFormatter = logging.Formatter('%(asctime)s - %(filename)s - %(levelname)s: %(message)s')
|
| 52 |
+
logger = logging.getLogger()
|
| 53 |
+
logger.setLevel(logging.INFO)
|
| 54 |
+
fHandler = logging.FileHandler(filename, mode='w')
|
| 55 |
+
fHandler.setFormatter(logFormatter)
|
| 56 |
+
logger.addHandler(fHandler)
|
| 57 |
+
cHandler = logging.StreamHandler()
|
| 58 |
+
cHandler.setFormatter(logFormatter)
|
| 59 |
+
logger.addHandler(cHandler)
|
| 60 |
+
|
| 61 |
+
def cal_eta(time0, cur_iter, total_iter):
|
| 62 |
+
time_now = datetime.datetime.now().replace(microsecond=0)
|
| 63 |
+
scale = (total_iter - cur_iter) / float(max(cur_iter, 1))
|
| 64 |
+
delta = time_now - time0
|
| 65 |
+
eta = delta * scale
|
| 66 |
+
time_fin = time_now + eta
|
| 67 |
+
eta = time_fin.replace(microsecond=0) - time_now
|
| 68 |
+
return str(delta), str(eta)
|
| 69 |
+
|
| 70 |
+
def maybe_load(module, path, device):
|
| 71 |
+
if path is None or path == '':
|
| 72 |
+
return
|
| 73 |
+
state = torch.load(path, map_location=device)
|
| 74 |
+
module.load_state_dict(state, strict=False)
|
| 75 |
+
|
| 76 |
+
def train(cfg):
|
| 77 |
+
seed = args.seed
|
| 78 |
+
torch.manual_seed(seed)
|
| 79 |
+
np.random.seed(seed)
|
| 80 |
+
num_workers = args.num_workers
|
| 81 |
+
torch.cuda.set_device(args.local_rank)
|
| 82 |
+
dist.init_process_group(backend=args.backend, timeout=datetime.timedelta(minutes=50))
|
| 83 |
+
time0 = datetime.datetime.now().replace(microsecond=0)
|
| 84 |
+
num_classes = 9
|
| 85 |
+
train_path = args.train_path
|
| 86 |
+
val_path = args.val_path
|
| 87 |
+
HSI_input_shape = [args.input_size, args.input_size]
|
| 88 |
+
batch_size = args.batch_size if args.batch_size is not None else 24
|
| 89 |
+
HSI_train_dataset = MarsDataset(root_dir=train_path, input_shape=HSI_input_shape, train=True)
|
| 90 |
+
HSI_val_dataset = MarsDataset(root_dir=val_path, input_shape=HSI_input_shape, train=False)
|
| 91 |
+
HSI_train_sampler = DistributedSampler(HSI_train_dataset)
|
| 92 |
+
HSI_train_loader = DataLoader(HSI_train_dataset, batch_size=batch_size, num_workers=num_workers, pin_memory=True, drop_last=True, sampler=HSI_train_sampler, prefetch_factor=2)
|
| 93 |
+
HSI_val_loader = DataLoader(HSI_val_dataset, batch_size=batch_size, shuffle=False, num_workers=num_workers, pin_memory=True, drop_last=False)
|
| 94 |
+
device = torch.device('cuda', args.local_rank)
|
| 95 |
+
if args.local_rank == 0:
|
| 96 |
+
print('%d GPUs are available' % torch.cuda.device_count())
|
| 97 |
+
wavelength_1, wavelength_2, wavelength_3 = 600.0, 540.0, 460.0
|
| 98 |
+
EVPL_model = EVPL(lamda_max_1=wavelength_1, lamda_max_2=wavelength_2, lamda_max_3=wavelength_3, device=device)
|
| 99 |
+
maybe_load(EVPL_model, args.evpl_pretrain, device)
|
| 100 |
+
EVPL_model.to(device)
|
| 101 |
+
EVPL_model = DistributedDataParallel(EVPL_model, device_ids=[args.local_rank], find_unused_parameters=True)
|
| 102 |
+
if args.encoder_type == 'mit_b0':
|
| 103 |
+
backbone = mit_b0()
|
| 104 |
+
elif args.encoder_type == 'mit_b1':
|
| 105 |
+
backbone = mit_b1()
|
| 106 |
+
elif args.encoder_type == 'mit_b3':
|
| 107 |
+
backbone = mit_b3()
|
| 108 |
+
elif args.encoder_type == 'mit_b5':
|
| 109 |
+
backbone = mit_b5()
|
| 110 |
+
else:
|
| 111 |
+
raise ValueError(args.encoder_type)
|
| 112 |
+
maybe_load(backbone, args.backbone_pretrain, device)
|
| 113 |
+
backbone.to(device)
|
| 114 |
+
backbone = DistributedDataParallel(backbone, device_ids=[args.local_rank], find_unused_parameters=True)
|
| 115 |
+
seg_decoder = SegFormerHead(feature_strides=[4, 8, 16, 32], in_channels=backbone.module.embed_dims, embedding_dim=256, num_classes=num_classes)
|
| 116 |
+
maybe_load(seg_decoder, args.head_pretrain, device)
|
| 117 |
+
seg_decoder.to(device)
|
| 118 |
+
seg_decoder = DistributedDataParallel(seg_decoder, device_ids=[args.local_rank], find_unused_parameters=True)
|
| 119 |
+
criterion = torch.nn.CrossEntropyLoss(ignore_index=255).to(device)
|
| 120 |
+
backbone_optimizer = torch.optim.Adam(backbone.parameters(), lr=1e-4)
|
| 121 |
+
head_optimizer = torch.optim.SGD(seg_decoder.parameters(), lr=5e-4, momentum=0.9, weight_decay=0.0005)
|
| 122 |
+
evpl_optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, EVPL_model.parameters()), lr=2e-1)
|
| 123 |
+
backbone_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(backbone_optimizer, T_max=cfg.train.num_epoch)
|
| 124 |
+
head_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(head_optimizer, T_max=cfg.train.num_epoch)
|
| 125 |
+
evpl_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(evpl_optimizer, T_max=cfg.train.num_epoch)
|
| 126 |
+
global_step = 0
|
| 127 |
+
for epoch in range(cfg.train.num_epoch):
|
| 128 |
+
HSI_train_sampler.set_epoch(epoch)
|
| 129 |
+
for step, data in enumerate(HSI_train_loader):
|
| 130 |
+
backbone.train()
|
| 131 |
+
seg_decoder.train()
|
| 132 |
+
EVPL_model.train()
|
| 133 |
+
hsi, rgb, label, mask = data
|
| 134 |
+
hsi = hsi.to(device, non_blocking=True)
|
| 135 |
+
label = label.to(device, non_blocking=True)
|
| 136 |
+
features = backbone(EVPL_model(hsi))
|
| 137 |
+
seg_outputs = seg_decoder(features)
|
| 138 |
+
seg_outputs = F.interpolate(seg_outputs, size=label.shape[1:], mode='bilinear', align_corners=False)
|
| 139 |
+
seg_loss = criterion(seg_outputs, label.type(torch.long))
|
| 140 |
+
head_optimizer.zero_grad()
|
| 141 |
+
backbone_optimizer.zero_grad()
|
| 142 |
+
evpl_optimizer.zero_grad()
|
| 143 |
+
seg_loss.backward()
|
| 144 |
+
backbone_optimizer.step()
|
| 145 |
+
head_optimizer.step()
|
| 146 |
+
evpl_optimizer.step()
|
| 147 |
+
global_step += 1
|
| 148 |
+
if args.local_rank == 0:
|
| 149 |
+
delta, eta = cal_eta(time0, epoch + 1, cfg.train.num_epoch)
|
| 150 |
+
logging.info('Epoch: %d;step: %d;Elasped: %s;eta: %s;seg_loss: %f' % (epoch + 1, step + 1, delta, eta, seg_loss.item()))
|
| 151 |
+
if args.max_steps is not None and global_step >= args.max_steps:
|
| 152 |
+
if args.local_rank == 0:
|
| 153 |
+
logging.info('Reached max_steps=%d, stop training' % args.max_steps)
|
| 154 |
+
dist.destroy_process_group()
|
| 155 |
+
return True
|
| 156 |
+
backbone_scheduler.step()
|
| 157 |
+
head_scheduler.step()
|
| 158 |
+
evpl_scheduler.step()
|
| 159 |
+
if args.skip_val:
|
| 160 |
+
continue
|
| 161 |
+
train_accurate = segmentation_validation(backbone=backbone, seg_decoder=seg_decoder, EVPL_model=EVPL_model, criterion=criterion, data_loader=HSI_train_loader, num_classes=num_classes)
|
| 162 |
+
if args.local_rank == 0:
|
| 163 |
+
logging.info(train_accurate)
|
| 164 |
+
for name, param in EVPL_model.module.filter_spectral_response.named_parameters():
|
| 165 |
+
logging.info(f'Epoch {epoch + 1} - {name} weights: {param.data}')
|
| 166 |
+
if (epoch + 1) % cfg.train.eval_epoch == 0:
|
| 167 |
+
torch.save(EVPL_model.module.state_dict(), os.path.join(args.workdir, 'mars_rrbb_Epoch{}.pth'.format(epoch + 1)))
|
| 168 |
+
if args.local_rank == 0:
|
| 169 |
+
logging.info('Validating...')
|
| 170 |
+
val_accurate = segmentation_validation(backbone=backbone, seg_decoder=seg_decoder, EVPL_model=EVPL_model, criterion=criterion, data_loader=HSI_val_loader, num_classes=num_classes)
|
| 171 |
+
if args.local_rank == 0:
|
| 172 |
+
logging.info(val_accurate)
|
| 173 |
+
dist.destroy_process_group()
|
| 174 |
+
return True
|
| 175 |
+
|
| 176 |
+
if __name__ == '__main__':
|
| 177 |
+
parser = get_args_parser()
|
| 178 |
+
args = parser.parse_args()
|
| 179 |
+
cfg = OmegaConf.load(args.config)
|
| 180 |
+
if not os.path.exists(args.workdir):
|
| 181 |
+
os.makedirs(args.workdir)
|
| 182 |
+
if args.local_rank == 0:
|
| 183 |
+
log_dir = os.path.join(args.workdir, 'Mars_rrbb.log')
|
| 184 |
+
open(log_dir, 'w').close()
|
| 185 |
+
setup_logger(filename=log_dir)
|
| 186 |
+
logging.info('\nconfigs: %s' % cfg)
|
| 187 |
+
setup_seed(args.seed)
|
| 188 |
+
train(cfg=cfg)
|
mhsi_exp.py
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
from itertools import cycle
|
| 4 |
+
import torchvision
|
| 5 |
+
import datetime
|
| 6 |
+
file_path = os.path.abspath(__file__)
|
| 7 |
+
cur_path = os.path.dirname(file_path)
|
| 8 |
+
project_path = os.path.dirname(cur_path)
|
| 9 |
+
sys.path.append(project_path)
|
| 10 |
+
import argparse
|
| 11 |
+
import datetime
|
| 12 |
+
import logging
|
| 13 |
+
import os
|
| 14 |
+
import random
|
| 15 |
+
import numpy as np
|
| 16 |
+
import torch
|
| 17 |
+
import torch.nn as nn
|
| 18 |
+
import torch.distributed as dist
|
| 19 |
+
import torch.nn.functional as F
|
| 20 |
+
import torchvision.models as models
|
| 21 |
+
from omegaconf import OmegaConf
|
| 22 |
+
from torch.nn.parallel import DistributedDataParallel
|
| 23 |
+
from torch.utils.data import DataLoader
|
| 24 |
+
from torch.utils.data.distributed import DistributedSampler
|
| 25 |
+
from tqdm import tqdm
|
| 26 |
+
from models.backbone.mix_transformer import mit_b0, mit_b3, mit_b5, mit_b1
|
| 27 |
+
from models.HSI_to_RGB.mhsi_EVPL import EVPL
|
| 28 |
+
from models.decoder.segformer_head import SegFormerHead
|
| 29 |
+
from util import fid
|
| 30 |
+
from util.validation import seg_validate_for_HSI2, segmentation_validation
|
| 31 |
+
from util.optimizer import PolyWarmupAdamW
|
| 32 |
+
import json
|
| 33 |
+
from dataloader.Data_Generate import Data_Generate_Bile
|
| 34 |
+
from dataloader.argument import Transform
|
| 35 |
+
|
| 36 |
+
def get_args_parser():
|
| 37 |
+
parser = argparse.ArgumentParser()
|
| 38 |
+
parser.add_argument('--config', default='configs/mhsi.yaml', type=str, help='config')
|
| 39 |
+
parser.add_argument('--local_rank', default=os.getenv('LOCAL_RANK', 0), type=int, help='local_rank')
|
| 40 |
+
parser.add_argument('--backend', default='nccl')
|
| 41 |
+
parser.add_argument('--workdir', type=str, default='work_dir/human')
|
| 42 |
+
parser.add_argument('--backbone_pretrain', default='', help='the pretrained segmentor')
|
| 43 |
+
parser.add_argument('--head_pretrain', default='', help='the pretrained segmentor')
|
| 44 |
+
parser.add_argument('--evpl_pretrain', default='', help='the pretrained evpl')
|
| 45 |
+
parser.add_argument('--encoder_type', default='mit_b0', type=str, choices=['swin_b', 'swin_l', 'vit_b', 'vit_l', 'mit_b0', 'mit_b1', 'mit_b3', 'mit_b5'], help='Name of model to train')
|
| 46 |
+
parser.add_argument('--seed', default=42, type=int)
|
| 47 |
+
args = parser.parse_args()
|
| 48 |
+
if 'LOCAL_RANK' not in os.environ:
|
| 49 |
+
os.environ['LOCAL_RANK'] = str(args.local_rank)
|
| 50 |
+
return parser
|
| 51 |
+
|
| 52 |
+
def setup_seed(seed):
|
| 53 |
+
torch.manual_seed(seed)
|
| 54 |
+
torch.cuda.manual_seed_all(seed)
|
| 55 |
+
np.random.seed(seed)
|
| 56 |
+
random.seed(seed)
|
| 57 |
+
torch.backends.cudnn.deterministic = True
|
| 58 |
+
|
| 59 |
+
def setup_logger(filename):
|
| 60 |
+
logFormatter = logging.Formatter('%(asctime)s - %(filename)s - %(levelname)s: %(message)s')
|
| 61 |
+
logger = logging.getLogger()
|
| 62 |
+
logger.setLevel(logging.INFO)
|
| 63 |
+
fHandler = logging.FileHandler(filename, mode='w')
|
| 64 |
+
fHandler.setFormatter(logFormatter)
|
| 65 |
+
logger.addHandler(fHandler)
|
| 66 |
+
cHandler = logging.StreamHandler()
|
| 67 |
+
cHandler.setFormatter(logFormatter)
|
| 68 |
+
logger.addHandler(cHandler)
|
| 69 |
+
|
| 70 |
+
def cal_eta(time0, cur_iter, total_iter):
|
| 71 |
+
time_now = datetime.datetime.now()
|
| 72 |
+
time_now = time_now.replace(microsecond=0)
|
| 73 |
+
scale = (total_iter - cur_iter) / float(cur_iter)
|
| 74 |
+
delta = time_now - time0
|
| 75 |
+
eta = delta * scale
|
| 76 |
+
time_fin = time_now + eta
|
| 77 |
+
eta = time_fin.replace(microsecond=0) - time_now
|
| 78 |
+
return (str(delta), str(eta))
|
| 79 |
+
|
| 80 |
+
def count_parameters(model):
|
| 81 |
+
total_params = sum((p.numel() for p in model.parameters()))
|
| 82 |
+
trainable_params = sum((p.numel() for p in model.parameters() if p.requires_grad))
|
| 83 |
+
return (total_params, trainable_params)
|
| 84 |
+
|
| 85 |
+
def train(cfg):
|
| 86 |
+
seed = args.seed
|
| 87 |
+
torch.manual_seed(seed)
|
| 88 |
+
np.random.seed(seed)
|
| 89 |
+
num_workers = 4
|
| 90 |
+
torch.cuda.set_device(args.local_rank)
|
| 91 |
+
dist.init_process_group(backend=args.backend, timeout=datetime.timedelta(minutes=50), rank=args.local_rank, world_size=4)
|
| 92 |
+
time0 = datetime.datetime.now()
|
| 93 |
+
time0 = time0.replace(microsecond=0)
|
| 94 |
+
num_classes = 2
|
| 95 |
+
root_path = 'datasets/MHSI/'
|
| 96 |
+
dataset_hyper = 'MHSI'
|
| 97 |
+
dataset_mask = 'Mask'
|
| 98 |
+
dataset_divide = 'train_val_test.json'
|
| 99 |
+
images_root_path = os.path.join(root_path, dataset_hyper)
|
| 100 |
+
mask_root_path = os.path.join(root_path, dataset_mask)
|
| 101 |
+
dataset_json = os.path.join(root_path, dataset_divide)
|
| 102 |
+
with open(dataset_json, 'r') as load_f:
|
| 103 |
+
dataset_dict = json.load(load_f)
|
| 104 |
+
train_files = dataset_dict['train']
|
| 105 |
+
val_files = dataset_dict['val']
|
| 106 |
+
test_files = dataset_dict['test']
|
| 107 |
+
train_files = train_files + val_files
|
| 108 |
+
use_aug = True
|
| 109 |
+
principal_bands_num = -1
|
| 110 |
+
cutting = -1
|
| 111 |
+
val_transformer = None
|
| 112 |
+
local_rank = args.local_rank
|
| 113 |
+
torch.cuda.set_device(local_rank)
|
| 114 |
+
device = torch.device('cuda', local_rank)
|
| 115 |
+
batch = 8
|
| 116 |
+
train_images_path = [os.path.join(images_root_path, i) for i in train_files]
|
| 117 |
+
train_masks_path = [os.path.join(mask_root_path, f'{i[:-4]}.png') for i in train_files]
|
| 118 |
+
test_images_path = [os.path.join(images_root_path, i) for i in test_files]
|
| 119 |
+
test_masks_path = [os.path.join(mask_root_path, f'{i[:-4]}.png') for i in test_files]
|
| 120 |
+
train_db = Data_Generate_Bile(train_images_path, train_masks_path, transform=val_transformer, principal_bands_num=principal_bands_num, cutting=cutting)
|
| 121 |
+
train_sampler = DistributedSampler(train_db)
|
| 122 |
+
train_loader = DataLoader(train_db, sampler=train_sampler, batch_size=batch, num_workers=num_workers, drop_last=True)
|
| 123 |
+
test_db = Data_Generate_Bile(test_images_path, test_masks_path, transform=val_transformer, principal_bands_num=principal_bands_num, cutting=cutting)
|
| 124 |
+
test_sampler = DistributedSampler(test_db, shuffle=False)
|
| 125 |
+
test_loader = DataLoader(test_db, sampler=test_sampler, batch_size=batch, shuffle=False, num_workers=num_workers, drop_last=False)
|
| 126 |
+
device = torch.device('cuda')
|
| 127 |
+
print('%d GPUs are available:' % torch.cuda.device_count())
|
| 128 |
+
(wavelength_r, wavelength_g, wavelength_b) = (600.0, 540.0, 460.0)
|
| 129 |
+
|
| 130 |
+
def change_wavelength_to_channel(wavelength):
|
| 131 |
+
return (wavelength - 450) / 4 + 1
|
| 132 |
+
EVPL_model = EVPL(lamda_max_1=wavelength_r, lamda_max_2=wavelength_g, lamda_max_3=wavelength_b, device=device)
|
| 133 |
+
EVPL_model.to(device)
|
| 134 |
+
EVPL_model = DistributedDataParallel(EVPL_model, device_ids=[args.local_rank], find_unused_parameters=True)
|
| 135 |
+
if args.encoder_type == 'mit_b0':
|
| 136 |
+
backbone = mit_b0()
|
| 137 |
+
elif args.encoder_type == 'mit_b1':
|
| 138 |
+
backbone = mit_b1()
|
| 139 |
+
elif args.encoder_type == 'mit_b3':
|
| 140 |
+
backbone = mit_b3()
|
| 141 |
+
elif args.encoder_type == 'mit_b5':
|
| 142 |
+
backbone = mit_b5()
|
| 143 |
+
backbone.to(device)
|
| 144 |
+
backbone = DistributedDataParallel(backbone, device_ids=[args.local_rank], find_unused_parameters=True)
|
| 145 |
+
seg_decoder = SegFormerHead(feature_strides=[4, 8, 16, 32], in_channels=backbone.module.embed_dims, embedding_dim=256, num_classes=num_classes)
|
| 146 |
+
seg_decoder.to(device)
|
| 147 |
+
seg_decoder = DistributedDataParallel(seg_decoder, device_ids=[args.local_rank], find_unused_parameters=True)
|
| 148 |
+
logging.info('successfully load pretrain model')
|
| 149 |
+
if args.local_rank == 0:
|
| 150 |
+
(backbone_total, backbone_train) = count_parameters(backbone.module)
|
| 151 |
+
(seg_decoder_total, seg_decoder_train) = count_parameters(seg_decoder.module)
|
| 152 |
+
(evpl_total, evpl_train) = count_parameters(EVPL_model.module)
|
| 153 |
+
total_all = backbone_total + seg_decoder_total + evpl_total
|
| 154 |
+
train_all = backbone_train + seg_decoder_train + evpl_train
|
| 155 |
+
logging.info(f"\n{'=' * 70}")
|
| 156 |
+
logging.info(f"{'=' * 70}")
|
| 157 |
+
logging.info(f'Backbone: Total={backbone_total:>12,} Trainable={backbone_train:>12,}')
|
| 158 |
+
logging.info(f'SegDecoder: Total={seg_decoder_total:>12,} Trainable={seg_decoder_train:>12,}')
|
| 159 |
+
logging.info(f'EVPL: Total={evpl_total:>12,} Trainable={evpl_train:>12,}')
|
| 160 |
+
logging.info(f"{'-' * 70}")
|
| 161 |
+
logging.info(f'Total: Total={total_all:>12,} Trainable={train_all:>12,}')
|
| 162 |
+
logging.info(f"{'=' * 70}\n")
|
| 163 |
+
beta = 0.2
|
| 164 |
+
criterion = torch.nn.CrossEntropyLoss(ignore_index=255)
|
| 165 |
+
criterion = criterion.to(device)
|
| 166 |
+
backbone_optimizer = torch.optim.Adam(backbone.parameters(), lr=6e-05)
|
| 167 |
+
head_optimizer = torch.optim.SGD(seg_decoder.parameters(), lr=0.0005, momentum=0.9, weight_decay=0.0005)
|
| 168 |
+
evpl_optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, EVPL_model.parameters()), lr=0.3)
|
| 169 |
+
backbone_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(backbone_optimizer, T_max=cfg.train.num_epoch)
|
| 170 |
+
head_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(head_optimizer, T_max=cfg.train.num_epoch)
|
| 171 |
+
evpl_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(evpl_optimizer, T_max=cfg.train.num_epoch)
|
| 172 |
+
for epoch in range(cfg.train.num_epoch):
|
| 173 |
+
for (step, data) in enumerate(train_loader):
|
| 174 |
+
backbone.train()
|
| 175 |
+
seg_decoder.train()
|
| 176 |
+
EVPL_model.train()
|
| 177 |
+
(hsi, label) = data
|
| 178 |
+
hsi = hsi.to(device, non_blocking=True)
|
| 179 |
+
label = label.squeeze(1).type(torch.uint8).to(device, non_blocking=True)
|
| 180 |
+
features = backbone(EVPL_model(hsi))
|
| 181 |
+
seg_outputs = seg_decoder(features)
|
| 182 |
+
seg_outputs = F.interpolate(seg_outputs, size=label.shape[1:], mode='bilinear', align_corners=False)
|
| 183 |
+
seg_loss = criterion(seg_outputs, label.type(torch.long))
|
| 184 |
+
head_optimizer.zero_grad()
|
| 185 |
+
backbone_optimizer.zero_grad()
|
| 186 |
+
evpl_optimizer.zero_grad()
|
| 187 |
+
seg_loss.backward(retain_graph=True)
|
| 188 |
+
backbone_optimizer.step()
|
| 189 |
+
head_optimizer.step()
|
| 190 |
+
evpl_optimizer.step()
|
| 191 |
+
if args.local_rank == 0:
|
| 192 |
+
(delta, eta) = cal_eta(time0, epoch + 1, cfg.train.num_epoch)
|
| 193 |
+
logging.info('Epoch: %d;step: %d;Elasped: %s;eta: %s;seg_loss: %f' % (epoch + 1, step + 1, delta, eta, seg_loss.item()))
|
| 194 |
+
backbone_scheduler.step()
|
| 195 |
+
head_scheduler.step()
|
| 196 |
+
for (name, param) in EVPL_model.module.filter_spectral_response.named_parameters():
|
| 197 |
+
logging.info(f'Epoch {epoch + 1} - {name} weights: {param.data}')
|
| 198 |
+
torch.save(seg_decoder.module.state_dict(), os.path.join(args.workdir, 'head_binary_Epoch{}.pth'.format(epoch + 1)))
|
| 199 |
+
torch.save(backbone.module.state_dict(), os.path.join(args.workdir, 'backbone_binary_Epoch{}.pth'.format(epoch + 1)))
|
| 200 |
+
torch.save(EVPL_model.module.state_dict(), os.path.join(args.workdir, 'EVPL_binary_Epoch{}.pth'.format(epoch + 1)))
|
| 201 |
+
if (epoch + 1) % cfg.train.eval_epoch == 0:
|
| 202 |
+
if args.local_rank == 0:
|
| 203 |
+
logging.info('Validating...')
|
| 204 |
+
val_accurate = segmentation_validation(backbone=backbone, seg_decoder=seg_decoder, EVPL_model=EVPL_model, criterion=criterion, data_loader=test_loader, num_classes=num_classes)
|
| 205 |
+
if args.local_rank == 0:
|
| 206 |
+
logging.info(val_accurate)
|
| 207 |
+
return True
|
| 208 |
+
if __name__ == '__main__':
|
| 209 |
+
args = get_args_parser()
|
| 210 |
+
args = args.parse_args()
|
| 211 |
+
cfg = OmegaConf.load(args.config)
|
| 212 |
+
if not os.path.exists(args.workdir):
|
| 213 |
+
os.makedirs(args.workdir)
|
| 214 |
+
if args.local_rank == 0:
|
| 215 |
+
log_dir = os.path.join(args.workdir, 'human_binary.log')
|
| 216 |
+
file = open(log_dir, 'w')
|
| 217 |
+
file.close()
|
| 218 |
+
setup_logger(filename=log_dir)
|
| 219 |
+
logging.info('\nconfigs: %s' % cfg)
|
| 220 |
+
train(cfg=cfg)
|
minneapple_det_count_exp.py
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
MinnApple detection & counting with Opsin + MiT + decoder.
|
| 3 |
+
|
| 4 |
+
Detection : Opsin -> MiT -> SegFormerHead (semantic seg, mIoU/F1)
|
| 5 |
+
Counting : Opsin -> MiT -> CountingHead (global count regression, MAE/RMSE)
|
| 6 |
+
|
| 7 |
+
Opsin modes:
|
| 8 |
+
--opsin_mode fixed : RGBOpsinLayer with frozen λ_max
|
| 9 |
+
--opsin_mode trainable : RGBOpsinLayer with learnable λ_max
|
| 10 |
+
|
| 11 |
+
Example:
|
| 12 |
+
torchrun --nproc_per_node=1 minneapple_det_count_exp.py \\
|
| 13 |
+
--task detection --opsin_mode fixed --workdir work_dir/minne_det_fixed
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import argparse
|
| 17 |
+
import datetime
|
| 18 |
+
import json
|
| 19 |
+
import logging
|
| 20 |
+
import os
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
import torch
|
| 24 |
+
import torch.nn as nn
|
| 25 |
+
import torch.nn.functional as F
|
| 26 |
+
from omegaconf import OmegaConf
|
| 27 |
+
from torch.utils.data import DataLoader
|
| 28 |
+
|
| 29 |
+
from dataloader.minneapple_ninja import (
|
| 30 |
+
MinneAppleDetectionDataset,
|
| 31 |
+
MinneAppleCountingDataset,
|
| 32 |
+
detection_metrics,
|
| 33 |
+
counting_metrics,
|
| 34 |
+
)
|
| 35 |
+
from models.backbone.mix_transformer import mit_b0
|
| 36 |
+
from models.decoder.segformer_head import SegFormerHead
|
| 37 |
+
from models.HSI_to_RGB.rgb_opsin import RGBOpsinLayer
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class CountingHead(nn.Module):
|
| 41 |
+
"""Global average pooling + MLP count regressor on MiT C4 features."""
|
| 42 |
+
|
| 43 |
+
def __init__(self, in_channels=256, hidden=128):
|
| 44 |
+
super().__init__()
|
| 45 |
+
self.pool = nn.AdaptiveAvgPool2d(1)
|
| 46 |
+
self.mlp = nn.Sequential(
|
| 47 |
+
nn.Linear(in_channels, hidden),
|
| 48 |
+
nn.ReLU(inplace=True),
|
| 49 |
+
nn.Linear(hidden, 1),
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
def forward(self, features):
|
| 53 |
+
x = features[-1]
|
| 54 |
+
x = self.pool(x).flatten(1)
|
| 55 |
+
return self.mlp(x).squeeze(-1)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class MinneAppleModel(nn.Module):
|
| 59 |
+
def __init__(self, task, opsin_trainable=False, num_classes=2):
|
| 60 |
+
super().__init__()
|
| 61 |
+
self.opsin = RGBOpsinLayer(trainable=opsin_trainable)
|
| 62 |
+
self.backbone = mit_b0()
|
| 63 |
+
self.task = task
|
| 64 |
+
if task == 'detection':
|
| 65 |
+
self.head = SegFormerHead(
|
| 66 |
+
feature_strides=[4, 8, 16, 32],
|
| 67 |
+
in_channels=self.backbone.embed_dims,
|
| 68 |
+
embedding_dim=256,
|
| 69 |
+
num_classes=num_classes,
|
| 70 |
+
)
|
| 71 |
+
else:
|
| 72 |
+
self.head = CountingHead(in_channels=self.backbone.embed_dims[-1])
|
| 73 |
+
|
| 74 |
+
def forward(self, x):
|
| 75 |
+
feat = self.backbone(self.opsin(x))
|
| 76 |
+
if self.task == 'detection':
|
| 77 |
+
return self.head(feat)
|
| 78 |
+
return self.head(feat)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def get_args():
|
| 82 |
+
p = argparse.ArgumentParser()
|
| 83 |
+
p.add_argument('--task', required=True, choices=['detection', 'counting'])
|
| 84 |
+
p.add_argument('--opsin_mode', default='fixed', choices=['fixed', 'trainable'])
|
| 85 |
+
p.add_argument('--data_root', default='/data/lyj/data/minneapple')
|
| 86 |
+
p.add_argument('--config', default='configs/minneapple.yaml')
|
| 87 |
+
p.add_argument('--workdir', default='work_dir/minneapple_det_count')
|
| 88 |
+
p.add_argument('--counting_max_train', type=int, default=10000,
|
| 89 |
+
help='Cap counting-train samples for feasible runtime')
|
| 90 |
+
p.add_argument('--seed', type=int, default=42)
|
| 91 |
+
return p.parse_args()
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def setup_logger(path):
|
| 95 |
+
fmt = logging.Formatter('%(asctime)s - %(levelname)s: %(message)s')
|
| 96 |
+
log = logging.getLogger()
|
| 97 |
+
log.setLevel(logging.INFO)
|
| 98 |
+
log.handlers.clear()
|
| 99 |
+
for h in (logging.FileHandler(path, mode='w'), logging.StreamHandler()):
|
| 100 |
+
h.setFormatter(fmt)
|
| 101 |
+
log.addHandler(h)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
@torch.no_grad()
|
| 105 |
+
def evaluate_detection(model, loader, device):
|
| 106 |
+
model.eval()
|
| 107 |
+
stats = {'iou': [], 'f1': []}
|
| 108 |
+
for img, mask in loader:
|
| 109 |
+
img = img.to(device)
|
| 110 |
+
logits = model(img)
|
| 111 |
+
logits = F.interpolate(logits, size=mask.shape[1:], mode='bilinear', align_corners=False)
|
| 112 |
+
pred = logits.argmax(dim=1).cpu().numpy()
|
| 113 |
+
gt = mask.numpy()
|
| 114 |
+
for i in range(pred.shape[0]):
|
| 115 |
+
m = detection_metrics(pred[i], gt[i])
|
| 116 |
+
stats['iou'].append(m['iou'])
|
| 117 |
+
stats['f1'].append(m['f1'])
|
| 118 |
+
return {'mIoU': float(np.mean(stats['iou'])), 'F1': float(np.mean(stats['f1']))}
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
@torch.no_grad()
|
| 122 |
+
def evaluate_counting(model, loader, device):
|
| 123 |
+
model.eval()
|
| 124 |
+
preds, gts = [], []
|
| 125 |
+
for img, count in loader:
|
| 126 |
+
img = img.to(device)
|
| 127 |
+
out = model(img)
|
| 128 |
+
preds.extend(out.cpu().numpy().tolist())
|
| 129 |
+
gts.extend(count.numpy().tolist())
|
| 130 |
+
return counting_metrics(preds, gts)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def train(args, cfg):
|
| 134 |
+
torch.manual_seed(args.seed)
|
| 135 |
+
np.random.seed(args.seed)
|
| 136 |
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 137 |
+
os.makedirs(args.workdir, exist_ok=True)
|
| 138 |
+
log_path = os.path.join(args.workdir, f'{args.task}_{args.opsin_mode}.log')
|
| 139 |
+
setup_logger(log_path)
|
| 140 |
+
logging.info('Task=%s opsin=%s device=%s', args.task, args.opsin_mode, device)
|
| 141 |
+
|
| 142 |
+
if args.task == 'detection':
|
| 143 |
+
train_ds = MinneAppleDetectionDataset(args.data_root, 'train', (512, 512))
|
| 144 |
+
val_ds = MinneAppleDetectionDataset(args.data_root, 'val', (512, 512))
|
| 145 |
+
bs = 4
|
| 146 |
+
else:
|
| 147 |
+
train_ds = MinneAppleCountingDataset(
|
| 148 |
+
args.data_root, 'train', (128, 128), max_samples=args.counting_max_train)
|
| 149 |
+
val_ds = MinneAppleCountingDataset(args.data_root, 'val', (128, 128))
|
| 150 |
+
bs = 32
|
| 151 |
+
|
| 152 |
+
train_loader = DataLoader(train_ds, batch_size=bs, shuffle=True, num_workers=4, drop_last=True)
|
| 153 |
+
val_loader = DataLoader(val_ds, batch_size=bs, shuffle=False, num_workers=4)
|
| 154 |
+
|
| 155 |
+
model = MinneAppleModel(
|
| 156 |
+
task=args.task,
|
| 157 |
+
opsin_trainable=(args.opsin_mode == 'trainable'),
|
| 158 |
+
).to(device)
|
| 159 |
+
|
| 160 |
+
if args.task == 'detection':
|
| 161 |
+
criterion = nn.CrossEntropyLoss()
|
| 162 |
+
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4, weight_decay=1e-4)
|
| 163 |
+
else:
|
| 164 |
+
criterion = nn.SmoothL1Loss()
|
| 165 |
+
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4, weight_decay=1e-4)
|
| 166 |
+
|
| 167 |
+
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=cfg.train.num_epoch)
|
| 168 |
+
best = {}
|
| 169 |
+
t0 = datetime.datetime.now()
|
| 170 |
+
|
| 171 |
+
for epoch in range(cfg.train.num_epoch):
|
| 172 |
+
model.train()
|
| 173 |
+
losses = []
|
| 174 |
+
for img, target in train_loader:
|
| 175 |
+
img = img.to(device)
|
| 176 |
+
optimizer.zero_grad()
|
| 177 |
+
if args.task == 'detection':
|
| 178 |
+
target = target.to(device)
|
| 179 |
+
out = model(img)
|
| 180 |
+
out = F.interpolate(out, size=target.shape[1:], mode='bilinear', align_corners=False)
|
| 181 |
+
loss = criterion(out, target.long())
|
| 182 |
+
else:
|
| 183 |
+
target = target.to(device)
|
| 184 |
+
out = model(img)
|
| 185 |
+
loss = criterion(out, target)
|
| 186 |
+
loss.backward()
|
| 187 |
+
optimizer.step()
|
| 188 |
+
losses.append(loss.item())
|
| 189 |
+
|
| 190 |
+
scheduler.step()
|
| 191 |
+
if (epoch + 1) % cfg.train.eval_epoch == 0 or epoch == 0:
|
| 192 |
+
if args.task == 'detection':
|
| 193 |
+
metrics = evaluate_detection(model, val_loader, device)
|
| 194 |
+
else:
|
| 195 |
+
metrics = evaluate_counting(model, val_loader, device)
|
| 196 |
+
key = 'mIoU' if args.task == 'detection' else 'MAE'
|
| 197 |
+
score = metrics[key]
|
| 198 |
+
better = (best.get(key) is None or
|
| 199 |
+
(key == 'mIoU' and score > best.get(key, 0)) or
|
| 200 |
+
(key == 'MAE' and score < best.get(key, 1e9)))
|
| 201 |
+
if better:
|
| 202 |
+
best = metrics
|
| 203 |
+
torch.save(model.state_dict(), os.path.join(args.workdir, 'best.pth'))
|
| 204 |
+
elapsed = datetime.datetime.now() - t0
|
| 205 |
+
logging.info('Epoch %d/%d loss=%.4f elapsed=%s metrics=%s best=%s',
|
| 206 |
+
epoch + 1, cfg.train.num_epoch, np.mean(losses), elapsed, metrics, best)
|
| 207 |
+
|
| 208 |
+
result = {
|
| 209 |
+
'task': args.task,
|
| 210 |
+
'opsin_mode': args.opsin_mode,
|
| 211 |
+
'decoder': 'SegFormerHead' if args.task == 'detection' else 'CountingHead',
|
| 212 |
+
'encoder': 'mit_b0',
|
| 213 |
+
'metrics': best,
|
| 214 |
+
}
|
| 215 |
+
with open(os.path.join(args.workdir, 'result.json'), 'w') as f:
|
| 216 |
+
json.dump(result, f, indent=2)
|
| 217 |
+
logging.info('Final result: %s', result)
|
| 218 |
+
return result
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
if __name__ == '__main__':
|
| 222 |
+
args = get_args()
|
| 223 |
+
cfg = OmegaConf.load(args.config)
|
| 224 |
+
train(args, cfg)
|
minneapple_exp.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import datetime
|
| 4 |
+
import argparse
|
| 5 |
+
import logging
|
| 6 |
+
import random
|
| 7 |
+
import numpy as np
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
import torch.distributed as dist
|
| 11 |
+
import torch.nn.functional as F
|
| 12 |
+
from dataloader.minneapple import MinneAppleHSIDataset
|
| 13 |
+
from models.backbone.mix_transformer import mit_b0, mit_b3, mit_b5, mit_b1
|
| 14 |
+
from models.HSI_to_RGB.minneapple_EVPL import EVPL, EVPLWithNormalization, ColorBlindEVPL
|
| 15 |
+
from models.decoder.segformer_head import SegFormerHead
|
| 16 |
+
from util.validation import segmentation_validation_fr
|
| 17 |
+
from omegaconf import OmegaConf
|
| 18 |
+
from torch.nn.parallel import DistributedDataParallel
|
| 19 |
+
from torch.utils.data import DataLoader
|
| 20 |
+
from torch.utils.data.distributed import DistributedSampler
|
| 21 |
+
from tqdm import tqdm
|
| 22 |
+
|
| 23 |
+
def get_args_parser():
|
| 24 |
+
parser = argparse.ArgumentParser(description='MinneApple Segmentation Training')
|
| 25 |
+
parser.add_argument('--config', default='configs/minneapple.yaml', type=str, help='')
|
| 26 |
+
parser.add_argument('--local_rank', default=os.getenv('LOCAL_RANK', 0), type=int, help='local_rank')
|
| 27 |
+
parser.add_argument('--backend', default='nccl', help='')
|
| 28 |
+
parser.add_argument('--workdir', type=str, default='work_dir/minneapple', help='')
|
| 29 |
+
parser.add_argument('--backbone_pretrain', default=None, help='backbone')
|
| 30 |
+
parser.add_argument('--head_pretrain', default=None, help='head')
|
| 31 |
+
parser.add_argument('--evpl_pretrain', default=None, help='EVPL')
|
| 32 |
+
parser.add_argument('--encoder_type', default='mit_b0', type=str, choices=['mit_b0', 'mit_b1', 'mit_b3', 'mit_b5'], help='backbone')
|
| 33 |
+
parser.add_argument('--seed', default=42, type=int, help='')
|
| 34 |
+
parser.add_argument('--evpl_mode', default='passthrough', type=str, choices=['passthrough', 'color_transform', 'colorblind'], help='EVPL')
|
| 35 |
+
parser.add_argument('--colorblind_type', default='protanopia', type=str, choices=['protanopia', 'deuteranopia', 'tritanopia', 'monochromacy'], help='(evpl_modecolorblind)')
|
| 36 |
+
if 'LOCAL_RANK' not in os.environ:
|
| 37 |
+
os.environ['LOCAL_RANK'] = os.getenv('SLURM_PROCID', '0')
|
| 38 |
+
return parser
|
| 39 |
+
|
| 40 |
+
def setup_seed(seed):
|
| 41 |
+
torch.manual_seed(seed)
|
| 42 |
+
torch.cuda.manual_seed_all(seed)
|
| 43 |
+
np.random.seed(seed)
|
| 44 |
+
random.seed(seed)
|
| 45 |
+
torch.backends.cudnn.deterministic = True
|
| 46 |
+
|
| 47 |
+
def setup_logger(filename):
|
| 48 |
+
logFormatter = logging.Formatter('%(asctime)s - %(filename)s - %(levelname)s: %(message)s')
|
| 49 |
+
logger = logging.getLogger()
|
| 50 |
+
logger.setLevel(logging.INFO)
|
| 51 |
+
fHandler = logging.FileHandler(filename, mode='w', encoding='utf-8')
|
| 52 |
+
fHandler.setFormatter(logFormatter)
|
| 53 |
+
logger.addHandler(fHandler)
|
| 54 |
+
cHandler = logging.StreamHandler()
|
| 55 |
+
cHandler.setFormatter(logFormatter)
|
| 56 |
+
logger.addHandler(cHandler)
|
| 57 |
+
|
| 58 |
+
def cal_eta(time0, cur_iter, total_iter):
|
| 59 |
+
time_now = datetime.datetime.now()
|
| 60 |
+
time_now = time_now.replace(microsecond=0)
|
| 61 |
+
scale = (total_iter - cur_iter) / float(cur_iter)
|
| 62 |
+
delta = time_now - time0
|
| 63 |
+
eta = delta * scale
|
| 64 |
+
time_fin = time_now + eta
|
| 65 |
+
eta = time_fin.replace(microsecond=0) - time_now
|
| 66 |
+
return (str(delta), str(eta))
|
| 67 |
+
|
| 68 |
+
def train(cfg, args):
|
| 69 |
+
seed = args.seed
|
| 70 |
+
torch.manual_seed(seed)
|
| 71 |
+
np.random.seed(seed)
|
| 72 |
+
num_workers = cfg.train.get('num_workers', 4)
|
| 73 |
+
torch.cuda.set_device(args.local_rank)
|
| 74 |
+
dist.init_process_group(backend=args.backend, timeout=datetime.timedelta(minutes=50))
|
| 75 |
+
time0 = datetime.datetime.now()
|
| 76 |
+
time0 = time0.replace(microsecond=0)
|
| 77 |
+
num_classes = cfg.dataset.num_classes
|
| 78 |
+
data_path = cfg.dataset.root_dir
|
| 79 |
+
input_shape = cfg.dataset.input_shape
|
| 80 |
+
train_dataset = MinneAppleHSIDataset(root_dir=data_path, input_shape=input_shape, train=True, augment=True)
|
| 81 |
+
val_dataset = MinneAppleHSIDataset(root_dir=data_path, input_shape=input_shape, train=False, augment=False)
|
| 82 |
+
train_sampler = DistributedSampler(train_dataset)
|
| 83 |
+
train_loader = DataLoader(train_dataset, batch_size=cfg.train.samples_per_gpu, shuffle=False, num_workers=num_workers, pin_memory=True, drop_last=True, sampler=train_sampler, prefetch_factor=4)
|
| 84 |
+
val_loader = DataLoader(val_dataset, batch_size=cfg.val.batch_size, shuffle=False, num_workers=num_workers, pin_memory=True, drop_last=False)
|
| 85 |
+
device = torch.device('cuda')
|
| 86 |
+
if args.local_rank == 0:
|
| 87 |
+
logging.info(f'{torch.cuda.device_count()} GPUs are available')
|
| 88 |
+
(wavelength_r, wavelength_g, wavelength_b) = (425.0, 540.0, 580.0)
|
| 89 |
+
if args.evpl_mode == 'colorblind':
|
| 90 |
+
EVPL_model = EVPLWithNormalization(lamda_max_1=wavelength_r, lamda_max_2=wavelength_g, lamda_max_3=wavelength_b, device=device, num_channels=31, use_isp=cfg.evpl.get('use_isp', False))
|
| 91 |
+
else:
|
| 92 |
+
EVPL_model = EVPL(lamda_max_1=wavelength_r, lamda_max_2=wavelength_g, lamda_max_3=wavelength_b, device=device, num_channels=31, use_isp=cfg.evpl.get('use_isp', False))
|
| 93 |
+
if args.evpl_pretrain is not None:
|
| 94 |
+
EVPL_model_dict = EVPL_model.state_dict()
|
| 95 |
+
EVPL_pre_train_dict = torch.load(args.evpl_pretrain, map_location=device)
|
| 96 |
+
EVPL_model_dict.update(EVPL_pre_train_dict)
|
| 97 |
+
EVPL_model.load_state_dict(EVPL_model_dict)
|
| 98 |
+
EVPL_model.to(device)
|
| 99 |
+
EVPL_model = DistributedDataParallel(EVPL_model, device_ids=[args.local_rank], find_unused_parameters=True)
|
| 100 |
+
if args.encoder_type == 'mit_b0':
|
| 101 |
+
backbone = mit_b0()
|
| 102 |
+
elif args.encoder_type == 'mit_b1':
|
| 103 |
+
backbone = mit_b1()
|
| 104 |
+
elif args.encoder_type == 'mit_b3':
|
| 105 |
+
backbone = mit_b3()
|
| 106 |
+
elif args.encoder_type == 'mit_b5':
|
| 107 |
+
backbone = mit_b5()
|
| 108 |
+
if args.backbone_pretrain is not None:
|
| 109 |
+
backbone_dict = backbone.state_dict()
|
| 110 |
+
backbone_pre_train_dict = torch.load(args.backbone_pretrain, map_location=device)
|
| 111 |
+
backbone_dict.update(backbone_pre_train_dict)
|
| 112 |
+
backbone.load_state_dict(backbone_dict)
|
| 113 |
+
if args.local_rank == 0:
|
| 114 |
+
logging.info(f'Loaded backbone pretrain from: {args.backbone_pretrain}')
|
| 115 |
+
backbone.to(device)
|
| 116 |
+
backbone = DistributedDataParallel(backbone, device_ids=[args.local_rank], find_unused_parameters=True)
|
| 117 |
+
seg_decoder = SegFormerHead(feature_strides=[4, 8, 16, 32], in_channels=backbone.module.embed_dims, embedding_dim=256, num_classes=num_classes)
|
| 118 |
+
if args.head_pretrain is not None:
|
| 119 |
+
seg_decoder_dict = seg_decoder.state_dict()
|
| 120 |
+
seg_decoder_pre_train_dict = torch.load(args.head_pretrain, map_location=device)
|
| 121 |
+
pretrain_dict = {k: v for (k, v) in seg_decoder_pre_train_dict.items() if k in seg_decoder_dict and v.shape == seg_decoder_dict[k].shape}
|
| 122 |
+
seg_decoder_dict.update(pretrain_dict)
|
| 123 |
+
seg_decoder.load_state_dict(seg_decoder_dict)
|
| 124 |
+
if args.local_rank == 0:
|
| 125 |
+
logging.info(f'Loaded head pretrain from: {args.head_pretrain}')
|
| 126 |
+
seg_decoder.to(device)
|
| 127 |
+
seg_decoder = DistributedDataParallel(seg_decoder, device_ids=[args.local_rank], find_unused_parameters=True)
|
| 128 |
+
if args.local_rank == 0:
|
| 129 |
+
logging.info('Models initialized successfully')
|
| 130 |
+
criterion = nn.CrossEntropyLoss(ignore_index=255)
|
| 131 |
+
criterion = criterion.to(device)
|
| 132 |
+
backbone_optimizer = torch.optim.Adam(backbone.parameters(), lr=cfg.optimizer.learning_rate)
|
| 133 |
+
head_optimizer = torch.optim.SGD(seg_decoder.parameters(), lr=cfg.head_optimizer.learning_rate, momentum=cfg.head_optimizer.momentum, weight_decay=cfg.head_optimizer.weight_decay)
|
| 134 |
+
evpl_optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, EVPL_model.parameters()), lr=cfg.evpl_optimizer.learning_rate)
|
| 135 |
+
backbone_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(backbone_optimizer, T_max=cfg.train.num_epoch)
|
| 136 |
+
head_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(head_optimizer, T_max=cfg.train.num_epoch)
|
| 137 |
+
evpl_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(evpl_optimizer, T_max=cfg.train.num_epoch)
|
| 138 |
+
best_miou = 0.0
|
| 139 |
+
for epoch in range(cfg.train.num_epoch):
|
| 140 |
+
train_sampler.set_epoch(epoch)
|
| 141 |
+
for (step, data) in enumerate(train_loader):
|
| 142 |
+
backbone.train()
|
| 143 |
+
seg_decoder.train()
|
| 144 |
+
EVPL_model.train()
|
| 145 |
+
(hsi, labels) = data
|
| 146 |
+
print('hsi', hsi.shape)
|
| 147 |
+
images = hsi.to(device, non_blocking=True)
|
| 148 |
+
labels = labels.to(device, non_blocking=True)
|
| 149 |
+
features = backbone(EVPL_model(images))
|
| 150 |
+
seg_outputs = seg_decoder(features)
|
| 151 |
+
seg_outputs = F.interpolate(seg_outputs, size=labels.shape[1:], mode='bilinear', align_corners=False)
|
| 152 |
+
seg_loss = criterion(seg_outputs, labels.long())
|
| 153 |
+
head_optimizer.zero_grad()
|
| 154 |
+
backbone_optimizer.zero_grad()
|
| 155 |
+
evpl_optimizer.zero_grad()
|
| 156 |
+
seg_loss.backward()
|
| 157 |
+
torch.nn.utils.clip_grad_norm_(EVPL_model.parameters(), max_norm=1.0)
|
| 158 |
+
backbone_optimizer.step()
|
| 159 |
+
head_optimizer.step()
|
| 160 |
+
evpl_optimizer.step()
|
| 161 |
+
if args.local_rank == 0:
|
| 162 |
+
(delta, eta) = cal_eta(time0, epoch * len(train_loader) + step + 1, cfg.train.num_epoch * len(train_loader))
|
| 163 |
+
logging.info(f'Epoch: {epoch + 1}; Step: {step + 1}/{len(train_loader)}; Elapsed: {delta}; ETA: {eta}; Loss: {seg_loss.item():.4f}')
|
| 164 |
+
backbone_scheduler.step()
|
| 165 |
+
head_scheduler.step()
|
| 166 |
+
evpl_scheduler.step()
|
| 167 |
+
if (epoch + 1) % cfg.train.eval_epoch == 0:
|
| 168 |
+
if args.local_rank == 0:
|
| 169 |
+
logging.info('Validating...')
|
| 170 |
+
val_result = segmentation_validation_fr(backbone=backbone, seg_decoder=seg_decoder, EVPL_model=EVPL_model, criterion=criterion, data_loader=val_loader, num_classes=num_classes)
|
| 171 |
+
if args.local_rank == 0:
|
| 172 |
+
logging.info(f'Validation Result: {val_result}')
|
| 173 |
+
current_miou = val_result['Mean IoU']
|
| 174 |
+
if current_miou > best_miou:
|
| 175 |
+
best_miou = current_miou
|
| 176 |
+
torch.save(backbone.module.state_dict(), os.path.join(args.workdir, 'best_backbone.pth'))
|
| 177 |
+
torch.save(seg_decoder.module.state_dict(), os.path.join(args.workdir, 'best_head.pth'))
|
| 178 |
+
torch.save(EVPL_model.module.state_dict(), os.path.join(args.workdir, 'best_evpl.pth'))
|
| 179 |
+
logging.info(f'Saved best model with mIoU: {best_miou:.4f}')
|
| 180 |
+
torch.save(backbone.module.state_dict(), os.path.join(args.workdir, f'backbone_Epoch{epoch + 1}.pth'))
|
| 181 |
+
torch.save(seg_decoder.module.state_dict(), os.path.join(args.workdir, f'head_Epoch{epoch + 1}.pth'))
|
| 182 |
+
torch.save(EVPL_model.module.state_dict(), os.path.join(args.workdir, f'evpl_Epoch{epoch + 1}.pth'))
|
| 183 |
+
if args.local_rank == 0:
|
| 184 |
+
logging.info(f'Training completed! Best mIoU: {best_miou:.4f}')
|
| 185 |
+
return True
|
| 186 |
+
file_path = os.path.abspath(__file__)
|
| 187 |
+
cur_path = os.path.dirname(file_path)
|
| 188 |
+
project_path = os.path.dirname(cur_path)
|
| 189 |
+
sys.path.append(project_path)
|
| 190 |
+
if __name__ == '__main__':
|
| 191 |
+
parser = get_args_parser()
|
| 192 |
+
args = parser.parse_args()
|
| 193 |
+
cfg = OmegaConf.load(args.config)
|
| 194 |
+
if not os.path.exists(args.workdir):
|
| 195 |
+
os.makedirs(args.workdir)
|
| 196 |
+
if args.local_rank == 0:
|
| 197 |
+
log_dir = os.path.join(args.workdir, 'minneapple_exp.log')
|
| 198 |
+
setup_logger(filename=log_dir)
|
| 199 |
+
logging.info(f'\nConfigs: {cfg}')
|
| 200 |
+
logging.info(f'EVPL Mode: {args.evpl_mode}')
|
| 201 |
+
if args.evpl_mode == 'colorblind':
|
| 202 |
+
logging.info(f'Colorblind Type: {args.colorblind_type}')
|
| 203 |
+
setup_seed(args.seed)
|
| 204 |
+
train(cfg=cfg, args=args)
|
models/HSI_to_RGB/Mars3.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
import numpy as np
|
| 6 |
+
from .invertible_isp_model.model import InvISPNet
|
| 7 |
+
|
| 8 |
+
wavelengths = np.array([400, 410, 420, 430, 440, 450, 460, 470, 480, 490, 500, 510, 520, 530, 540, 550, 560, 570, 580, 590, 600, 610, 620, 630, 640, 650, 660, 670, 680, 690, 700])
|
| 9 |
+
|
| 10 |
+
class EVPL(nn.Module):
|
| 11 |
+
|
| 12 |
+
def __init__(self, lamda_max_1, lamda_max_2, lamda_max_3, device):
|
| 13 |
+
super(EVPL, self).__init__()
|
| 14 |
+
self.filter_spectral_response = Gaussian_kernel_conv2d(lamda_max_1, lamda_max_2, lamda_max_3, device)
|
| 15 |
+
self.multi_to_rgb = nn.Conv2d(3, 3, kernel_size=(1, 1))
|
| 16 |
+
self.InvISPNet = InvISPNet()
|
| 17 |
+
|
| 18 |
+
def forward(self, x):
|
| 19 |
+
x = self.filter_spectral_response(x)
|
| 20 |
+
return x
|
| 21 |
+
|
| 22 |
+
class Gaussian_kernel_conv2d(nn.Module):
|
| 23 |
+
|
| 24 |
+
def __init__(self, lamda_max_1, lamda_max_2, lamda_max_3, device):
|
| 25 |
+
super(Gaussian_kernel_conv2d, self).__init__()
|
| 26 |
+
self.lamda_max_1 = nn.Parameter(torch.tensor(lamda_max_1, device=device), requires_grad=True)
|
| 27 |
+
self.lamda_max_2 = nn.Parameter(torch.tensor(lamda_max_2, device=device), requires_grad=True)
|
| 28 |
+
self.lamda_max_3 = nn.Parameter(torch.tensor(lamda_max_3, device=device), requires_grad=True)
|
| 29 |
+
self.wavelengths = torch.tensor(wavelengths, dtype=torch.float32, device=device, requires_grad=False)
|
| 30 |
+
self.std = 10.0
|
| 31 |
+
|
| 32 |
+
def forward(self, input):
|
| 33 |
+
if torch.isnan(input).any():
|
| 34 |
+
input = torch.nan_to_num(input, nan=0.0)
|
| 35 |
+
std = self.std
|
| 36 |
+
x = self.wavelengths
|
| 37 |
+
kernel_weight_1 = 1 / (std * (2 * math.pi) ** 0.5) * torch.exp(-(x - self.lamda_max_1) ** 2 / (2 * std ** 2)).unsqueeze(0).unsqueeze(2).unsqueeze(3)
|
| 38 |
+
kernel_weight_2 = 1 / (std * (2 * math.pi) ** 0.5) * torch.exp(-(x - self.lamda_max_2) ** 2 / (2 * std ** 2)).unsqueeze(0).unsqueeze(2).unsqueeze(3)
|
| 39 |
+
kernel_weight_3 = 1 / (std * (2 * math.pi) ** 0.5) * torch.exp(-(x - self.lamda_max_3) ** 2 / (2 * std ** 2)).unsqueeze(0).unsqueeze(2).unsqueeze(3)
|
| 40 |
+
kernel = torch.cat([kernel_weight_1, kernel_weight_2, kernel_weight_3], dim=0)
|
| 41 |
+
output = F.conv2d(input, kernel)
|
| 42 |
+
if torch.isnan(output).any():
|
| 43 |
+
output = torch.nan_to_num(output, nan=0.0)
|
| 44 |
+
return output
|
models/HSI_to_RGB/__init__.py
ADDED
|
File without changes
|
models/HSI_to_RGB/evpl_factory.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Unified EVPL / opsin-layer factory for MODID and MHSI experiments."""
|
| 2 |
+
|
| 3 |
+
OPSIN_MODES = ('free', 'opsin_fixed', 'opsin_train')
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def _set_lambda_trainable(evpl_module, trainable: bool):
|
| 7 |
+
g = evpl_module.filter_spectral_response
|
| 8 |
+
for name in ('lamda_max_1', 'lamda_max_2', 'lamda_max_3'):
|
| 9 |
+
if hasattr(g, name):
|
| 10 |
+
p = getattr(g, name)
|
| 11 |
+
p.requires_grad = trainable
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def build_evpl(dataset: str, opsin_mode: str, device, wavelengths=(600.0, 540.0, 460.0)):
|
| 15 |
+
"""
|
| 16 |
+
dataset: 'modid' | 'mhsi'
|
| 17 |
+
opsin_mode:
|
| 18 |
+
- free : FreeConv 1×1 spectral projection (fully learnable)
|
| 19 |
+
- opsin_fixed : Gaussian opsin, λ_max frozen
|
| 20 |
+
- opsin_train : Gaussian opsin, λ_max learnable
|
| 21 |
+
"""
|
| 22 |
+
if opsin_mode not in OPSIN_MODES:
|
| 23 |
+
raise ValueError(f"opsin_mode must be one of {OPSIN_MODES}")
|
| 24 |
+
|
| 25 |
+
w1, w2, w3 = wavelengths
|
| 26 |
+
|
| 27 |
+
if dataset == 'modid':
|
| 28 |
+
from models.HSI_to_RGB.modid_EVPL import EVPL
|
| 29 |
+
from models.HSI_to_RGB.modid_EVPL_ablation import EVPL_FreeConv
|
| 30 |
+
if opsin_mode == 'free':
|
| 31 |
+
return EVPL_FreeConv(device)
|
| 32 |
+
evpl = EVPL(w1, w2, w3, device)
|
| 33 |
+
_set_lambda_trainable(evpl, trainable=(opsin_mode == 'opsin_train'))
|
| 34 |
+
return evpl
|
| 35 |
+
|
| 36 |
+
if dataset == 'mhsi':
|
| 37 |
+
from models.HSI_to_RGB.mhsi_EVPL import EVPL
|
| 38 |
+
from models.HSI_to_RGB.mhsi_EVPL_ablation import EVPL_FreeConv
|
| 39 |
+
if opsin_mode == 'free':
|
| 40 |
+
return EVPL_FreeConv(device)
|
| 41 |
+
evpl = EVPL(w1, w2, w3, device)
|
| 42 |
+
_set_lambda_trainable(evpl, trainable=(opsin_mode == 'opsin_train'))
|
| 43 |
+
return evpl
|
| 44 |
+
|
| 45 |
+
raise ValueError(f"Unknown dataset '{dataset}'")
|
models/HSI_to_RGB/invertible_isp_model/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pass
|
models/HSI_to_RGB/invertible_isp_model/loss.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch.nn.functional as F
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
def l1_loss(output, target_rgb, target_raw, weight=1.0):
|
| 5 |
+
raw_loss = F.l1_loss(output['reconstruct_raw'], target_raw)
|
| 6 |
+
rgb_loss = F.l1_loss(output['reconstruct_rgb'], target_rgb)
|
| 7 |
+
total_loss = raw_loss + weight * rgb_loss
|
| 8 |
+
return (total_loss, raw_loss, rgb_loss)
|
| 9 |
+
|
| 10 |
+
def l2_loss(output, target_rgb, target_raw, weight=1.0):
|
| 11 |
+
raw_loss = F.mse_loss(output['reconstruct_raw'], target_raw)
|
| 12 |
+
rgb_loss = F.mse_loss(output['reconstruct_rgb'], target_rgb)
|
| 13 |
+
total_loss = raw_loss + weight * rgb_loss
|
| 14 |
+
return (total_loss, raw_loss, rgb_loss)
|
models/HSI_to_RGB/invertible_isp_model/model.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
import numpy as np
|
| 6 |
+
import torch.nn.init as init
|
| 7 |
+
from .modules import InvertibleConv1x1
|
| 8 |
+
|
| 9 |
+
def initialize_weights(net_l, scale=1):
|
| 10 |
+
if not isinstance(net_l, list):
|
| 11 |
+
net_l = [net_l]
|
| 12 |
+
for net in net_l:
|
| 13 |
+
for m in net.modules():
|
| 14 |
+
if isinstance(m, nn.Conv2d):
|
| 15 |
+
init.kaiming_normal_(m.weight, a=0, mode='fan_in')
|
| 16 |
+
m.weight.data *= scale
|
| 17 |
+
if m.bias is not None:
|
| 18 |
+
m.bias.data.zero_()
|
| 19 |
+
elif isinstance(m, nn.Linear):
|
| 20 |
+
init.kaiming_normal_(m.weight, a=0, mode='fan_in')
|
| 21 |
+
m.weight.data *= scale
|
| 22 |
+
if m.bias is not None:
|
| 23 |
+
m.bias.data.zero_()
|
| 24 |
+
elif isinstance(m, nn.BatchNorm2d):
|
| 25 |
+
init.constant_(m.weight, 1)
|
| 26 |
+
init.constant_(m.bias.data, 0.0)
|
| 27 |
+
|
| 28 |
+
def initialize_weights_xavier(net_l, scale=1):
|
| 29 |
+
if not isinstance(net_l, list):
|
| 30 |
+
net_l = [net_l]
|
| 31 |
+
for net in net_l:
|
| 32 |
+
for m in net.modules():
|
| 33 |
+
if isinstance(m, nn.Conv2d):
|
| 34 |
+
init.xavier_normal_(m.weight)
|
| 35 |
+
m.weight.data *= scale
|
| 36 |
+
if m.bias is not None:
|
| 37 |
+
m.bias.data.zero_()
|
| 38 |
+
elif isinstance(m, nn.Linear):
|
| 39 |
+
init.xavier_normal_(m.weight)
|
| 40 |
+
m.weight.data *= scale
|
| 41 |
+
if m.bias is not None:
|
| 42 |
+
m.bias.data.zero_()
|
| 43 |
+
elif isinstance(m, nn.BatchNorm2d):
|
| 44 |
+
init.constant_(m.weight, 1)
|
| 45 |
+
init.constant_(m.bias.data, 0.0)
|
| 46 |
+
|
| 47 |
+
class DenseBlock(nn.Module):
|
| 48 |
+
|
| 49 |
+
def __init__(self, channel_in, channel_out, init='xavier', gc=32, bias=True):
|
| 50 |
+
super(DenseBlock, self).__init__()
|
| 51 |
+
self.conv1 = nn.Conv2d(channel_in, gc, 3, 1, 1, bias=bias)
|
| 52 |
+
self.conv2 = nn.Conv2d(channel_in + gc, gc, 3, 1, 1, bias=bias)
|
| 53 |
+
self.conv3 = nn.Conv2d(channel_in + 2 * gc, gc, 3, 1, 1, bias=bias)
|
| 54 |
+
self.conv4 = nn.Conv2d(channel_in + 3 * gc, gc, 3, 1, 1, bias=bias)
|
| 55 |
+
self.conv5 = nn.Conv2d(channel_in + 4 * gc, channel_out, 3, 1, 1, bias=bias)
|
| 56 |
+
self.lrelu = nn.LeakyReLU(negative_slope=0.2, inplace=True)
|
| 57 |
+
if init == 'xavier':
|
| 58 |
+
initialize_weights_xavier([self.conv1, self.conv2, self.conv3, self.conv4], 0.1)
|
| 59 |
+
else:
|
| 60 |
+
initialize_weights([self.conv1, self.conv2, self.conv3, self.conv4], 0.1)
|
| 61 |
+
initialize_weights(self.conv5, 0)
|
| 62 |
+
|
| 63 |
+
def forward(self, x):
|
| 64 |
+
x1 = self.lrelu(self.conv1(x))
|
| 65 |
+
x2 = self.lrelu(self.conv2(torch.cat((x, x1), 1)))
|
| 66 |
+
x3 = self.lrelu(self.conv3(torch.cat((x, x1, x2), 1)))
|
| 67 |
+
x4 = self.lrelu(self.conv4(torch.cat((x, x1, x2, x3), 1)))
|
| 68 |
+
x5 = self.conv5(torch.cat((x, x1, x2, x3, x4), 1))
|
| 69 |
+
return x5
|
| 70 |
+
|
| 71 |
+
def subnet(net_structure, init='xavier'):
|
| 72 |
+
|
| 73 |
+
def constructor(channel_in, channel_out):
|
| 74 |
+
if net_structure == 'DBNet':
|
| 75 |
+
if init == 'xavier':
|
| 76 |
+
return DenseBlock(channel_in, channel_out, init)
|
| 77 |
+
else:
|
| 78 |
+
return DenseBlock(channel_in, channel_out)
|
| 79 |
+
else:
|
| 80 |
+
return None
|
| 81 |
+
return constructor
|
| 82 |
+
|
| 83 |
+
class InvBlock(nn.Module):
|
| 84 |
+
|
| 85 |
+
def __init__(self, subnet_constructor, channel_num, channel_split_num, clamp=0.8):
|
| 86 |
+
super(InvBlock, self).__init__()
|
| 87 |
+
self.split_len1 = channel_split_num
|
| 88 |
+
self.split_len2 = channel_num - channel_split_num
|
| 89 |
+
self.clamp = clamp
|
| 90 |
+
self.F = subnet_constructor(self.split_len2, self.split_len1)
|
| 91 |
+
self.G = subnet_constructor(self.split_len1, self.split_len2)
|
| 92 |
+
self.H = subnet_constructor(self.split_len1, self.split_len2)
|
| 93 |
+
in_channels = 3
|
| 94 |
+
self.invconv = InvertibleConv1x1(in_channels, LU_decomposed=True)
|
| 95 |
+
self.flow_permutation = lambda z, logdet, rev: self.invconv(z, logdet, rev)
|
| 96 |
+
|
| 97 |
+
def forward(self, x, rev=False):
|
| 98 |
+
if not rev:
|
| 99 |
+
(x, logdet) = self.flow_permutation(x, logdet=0, rev=False)
|
| 100 |
+
(x1, x2) = (x.narrow(1, 0, self.split_len1), x.narrow(1, self.split_len1, self.split_len2))
|
| 101 |
+
y1 = x1 + self.F(x2)
|
| 102 |
+
self.s = self.clamp * (torch.sigmoid(self.H(y1)) * 2 - 1)
|
| 103 |
+
y2 = x2.mul(torch.exp(self.s)) + self.G(y1)
|
| 104 |
+
out = torch.cat((y1, y2), 1)
|
| 105 |
+
else:
|
| 106 |
+
(x1, x2) = (x.narrow(1, 0, self.split_len1), x.narrow(1, self.split_len1, self.split_len2))
|
| 107 |
+
self.s = self.clamp * (torch.sigmoid(self.H(x1)) * 2 - 1)
|
| 108 |
+
y2 = (x2 - self.G(x1)).div(torch.exp(self.s))
|
| 109 |
+
y1 = x1 - self.F(y2)
|
| 110 |
+
x = torch.cat((y1, y2), 1)
|
| 111 |
+
(out, logdet) = self.flow_permutation(x, logdet=0, rev=True)
|
| 112 |
+
return out
|
| 113 |
+
|
| 114 |
+
class InvISPNet(nn.Module):
|
| 115 |
+
|
| 116 |
+
def __init__(self, channel_in=3, channel_out=3, subnet_constructor=subnet('DBNet'), block_num=8):
|
| 117 |
+
super(InvISPNet, self).__init__()
|
| 118 |
+
operations = []
|
| 119 |
+
current_channel = channel_in
|
| 120 |
+
channel_num = channel_in
|
| 121 |
+
channel_split_num = 1
|
| 122 |
+
for j in range(block_num):
|
| 123 |
+
b = InvBlock(subnet_constructor, channel_num, channel_split_num)
|
| 124 |
+
operations.append(b)
|
| 125 |
+
self.operations = nn.ModuleList(operations)
|
| 126 |
+
self.initialize()
|
| 127 |
+
|
| 128 |
+
def initialize(self):
|
| 129 |
+
for m in self.modules():
|
| 130 |
+
if isinstance(m, nn.Conv2d):
|
| 131 |
+
init.xavier_normal_(m.weight)
|
| 132 |
+
m.weight.data *= 1.0
|
| 133 |
+
if m.bias is not None:
|
| 134 |
+
m.bias.data.zero_()
|
| 135 |
+
elif isinstance(m, nn.Linear):
|
| 136 |
+
init.xavier_normal_(m.weight)
|
| 137 |
+
m.weight.data *= 1.0
|
| 138 |
+
if m.bias is not None:
|
| 139 |
+
m.bias.data.zero_()
|
| 140 |
+
elif isinstance(m, nn.BatchNorm2d):
|
| 141 |
+
init.constant_(m.weight, 1)
|
| 142 |
+
init.constant_(m.bias.data, 0.0)
|
| 143 |
+
|
| 144 |
+
def forward(self, x, rev=False):
|
| 145 |
+
out = x
|
| 146 |
+
if not rev:
|
| 147 |
+
for op in self.operations:
|
| 148 |
+
out = op.forward(out, rev)
|
| 149 |
+
else:
|
| 150 |
+
for op in reversed(self.operations):
|
| 151 |
+
out = op.forward(out, rev)
|
| 152 |
+
return out
|
models/HSI_to_RGB/invertible_isp_model/modules.py
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
from .utils import split_feature, compute_same_pad
|
| 6 |
+
|
| 7 |
+
def gaussian_p(mean, logs, x):
|
| 8 |
+
c = math.log(2 * math.pi)
|
| 9 |
+
return -0.5 * (logs * 2.0 + (x - mean) ** 2 / torch.exp(logs * 2.0) + c)
|
| 10 |
+
|
| 11 |
+
def gaussian_likelihood(mean, logs, x):
|
| 12 |
+
p = gaussian_p(mean, logs, x)
|
| 13 |
+
return torch.sum(p, dim=[1, 2, 3])
|
| 14 |
+
|
| 15 |
+
def gaussian_sample(mean, logs, temperature=1):
|
| 16 |
+
z = torch.normal(mean, torch.exp(logs) * temperature)
|
| 17 |
+
return z
|
| 18 |
+
|
| 19 |
+
def squeeze2d(input, factor):
|
| 20 |
+
if factor == 1:
|
| 21 |
+
return input
|
| 22 |
+
(B, C, H, W) = input.size()
|
| 23 |
+
assert H % factor == 0 and W % factor == 0, 'H or W modulo factor is not 0'
|
| 24 |
+
x = input.view(B, C, H // factor, factor, W // factor, factor)
|
| 25 |
+
x = x.permute(0, 1, 3, 5, 2, 4).contiguous()
|
| 26 |
+
x = x.view(B, C * factor * factor, H // factor, W // factor)
|
| 27 |
+
return x
|
| 28 |
+
|
| 29 |
+
def unsqueeze2d(input, factor):
|
| 30 |
+
if factor == 1:
|
| 31 |
+
return input
|
| 32 |
+
factor2 = factor ** 2
|
| 33 |
+
(B, C, H, W) = input.size()
|
| 34 |
+
assert C % factor2 == 0, 'C module factor squared is not 0'
|
| 35 |
+
x = input.view(B, C // factor2, factor, factor, H, W)
|
| 36 |
+
x = x.permute(0, 1, 4, 2, 5, 3).contiguous()
|
| 37 |
+
x = x.view(B, C // factor2, H * factor, W * factor)
|
| 38 |
+
return x
|
| 39 |
+
|
| 40 |
+
class _ActNorm(nn.Module):
|
| 41 |
+
|
| 42 |
+
def __init__(self, num_features, scale=1.0):
|
| 43 |
+
super().__init__()
|
| 44 |
+
size = [1, num_features, 1, 1]
|
| 45 |
+
self.bias = nn.Parameter(torch.zeros(*size))
|
| 46 |
+
self.logs = nn.Parameter(torch.zeros(*size))
|
| 47 |
+
self.num_features = num_features
|
| 48 |
+
self.scale = scale
|
| 49 |
+
self.inited = False
|
| 50 |
+
|
| 51 |
+
def initialize_parameters(self, input):
|
| 52 |
+
if not self.training:
|
| 53 |
+
raise ValueError('In Eval mode, but ActNorm not inited')
|
| 54 |
+
with torch.no_grad():
|
| 55 |
+
bias = -torch.mean(input.clone(), dim=[0, 2, 3], keepdim=True)
|
| 56 |
+
vars = torch.mean((input.clone() + bias) ** 2, dim=[0, 2, 3], keepdim=True)
|
| 57 |
+
logs = torch.log(self.scale / (torch.sqrt(vars) + 1e-06))
|
| 58 |
+
self.bias.data.copy_(bias.data)
|
| 59 |
+
self.logs.data.copy_(logs.data)
|
| 60 |
+
self.inited = True
|
| 61 |
+
|
| 62 |
+
def _center(self, input, reverse=False):
|
| 63 |
+
if reverse:
|
| 64 |
+
return input - self.bias
|
| 65 |
+
else:
|
| 66 |
+
return input + self.bias
|
| 67 |
+
|
| 68 |
+
def _scale(self, input, logdet=None, reverse=False):
|
| 69 |
+
if reverse:
|
| 70 |
+
input = input * torch.exp(-self.logs)
|
| 71 |
+
else:
|
| 72 |
+
input = input * torch.exp(self.logs)
|
| 73 |
+
if logdet is not None:
|
| 74 |
+
(b, c, h, w) = input.shape
|
| 75 |
+
dlogdet = torch.sum(self.logs) * h * w
|
| 76 |
+
if reverse:
|
| 77 |
+
dlogdet *= -1
|
| 78 |
+
logdet = logdet + dlogdet
|
| 79 |
+
return (input, logdet)
|
| 80 |
+
|
| 81 |
+
def forward(self, input, logdet=None, reverse=False):
|
| 82 |
+
self._check_input_dim(input)
|
| 83 |
+
if not self.inited:
|
| 84 |
+
self.initialize_parameters(input)
|
| 85 |
+
if reverse:
|
| 86 |
+
(input, logdet) = self._scale(input, logdet, reverse)
|
| 87 |
+
input = self._center(input, reverse)
|
| 88 |
+
else:
|
| 89 |
+
input = self._center(input, reverse)
|
| 90 |
+
(input, logdet) = self._scale(input, logdet, reverse)
|
| 91 |
+
return (input, logdet)
|
| 92 |
+
|
| 93 |
+
class ActNorm2d(_ActNorm):
|
| 94 |
+
|
| 95 |
+
def __init__(self, num_features, scale=1.0):
|
| 96 |
+
super().__init__(num_features, scale)
|
| 97 |
+
|
| 98 |
+
def _check_input_dim(self, input):
|
| 99 |
+
assert len(input.size()) == 4
|
| 100 |
+
assert input.size(1) == self.num_features, '[ActNorm]: input should be in shape as `BCHW`, channels should be {} rather than {}'.format(self.num_features, input.size())
|
| 101 |
+
|
| 102 |
+
class LinearZeros(nn.Module):
|
| 103 |
+
|
| 104 |
+
def __init__(self, in_channels, out_channels, logscale_factor=3):
|
| 105 |
+
super().__init__()
|
| 106 |
+
self.linear = nn.Linear(in_channels, out_channels)
|
| 107 |
+
self.linear.weight.data.zero_()
|
| 108 |
+
self.linear.bias.data.zero_()
|
| 109 |
+
self.logscale_factor = logscale_factor
|
| 110 |
+
self.logs = nn.Parameter(torch.zeros(out_channels))
|
| 111 |
+
|
| 112 |
+
def forward(self, input):
|
| 113 |
+
output = self.linear(input)
|
| 114 |
+
return output * torch.exp(self.logs * self.logscale_factor)
|
| 115 |
+
|
| 116 |
+
class Conv2d(nn.Module):
|
| 117 |
+
|
| 118 |
+
def __init__(self, in_channels, out_channels, kernel_size=(3, 3), stride=(1, 1), padding='same', do_actnorm=True, weight_std=0.05):
|
| 119 |
+
super().__init__()
|
| 120 |
+
if padding == 'same':
|
| 121 |
+
padding = compute_same_pad(kernel_size, stride)
|
| 122 |
+
elif padding == 'valid':
|
| 123 |
+
padding = 0
|
| 124 |
+
self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, bias=not do_actnorm)
|
| 125 |
+
self.conv.weight.data.normal_(mean=0.0, std=weight_std)
|
| 126 |
+
if not do_actnorm:
|
| 127 |
+
self.conv.bias.data.zero_()
|
| 128 |
+
else:
|
| 129 |
+
self.actnorm = ActNorm2d(out_channels)
|
| 130 |
+
self.do_actnorm = do_actnorm
|
| 131 |
+
|
| 132 |
+
def forward(self, input):
|
| 133 |
+
x = self.conv(input)
|
| 134 |
+
if self.do_actnorm:
|
| 135 |
+
(x, _) = self.actnorm(x)
|
| 136 |
+
return x
|
| 137 |
+
|
| 138 |
+
class Conv2dZeros(nn.Module):
|
| 139 |
+
|
| 140 |
+
def __init__(self, in_channels, out_channels, kernel_size=(3, 3), stride=(1, 1), padding='same', logscale_factor=3):
|
| 141 |
+
super().__init__()
|
| 142 |
+
if padding == 'same':
|
| 143 |
+
padding = compute_same_pad(kernel_size, stride)
|
| 144 |
+
elif padding == 'valid':
|
| 145 |
+
padding = 0
|
| 146 |
+
self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding)
|
| 147 |
+
self.conv.weight.data.zero_()
|
| 148 |
+
self.conv.bias.data.zero_()
|
| 149 |
+
self.logscale_factor = logscale_factor
|
| 150 |
+
self.logs = nn.Parameter(torch.zeros(out_channels, 1, 1))
|
| 151 |
+
|
| 152 |
+
def forward(self, input):
|
| 153 |
+
output = self.conv(input)
|
| 154 |
+
return output * torch.exp(self.logs * self.logscale_factor)
|
| 155 |
+
|
| 156 |
+
class Permute2d(nn.Module):
|
| 157 |
+
|
| 158 |
+
def __init__(self, num_channels, shuffle):
|
| 159 |
+
super().__init__()
|
| 160 |
+
self.num_channels = num_channels
|
| 161 |
+
self.indices = torch.arange(self.num_channels - 1, -1, -1, dtype=torch.long)
|
| 162 |
+
self.indices_inverse = torch.zeros(self.num_channels, dtype=torch.long)
|
| 163 |
+
for i in range(self.num_channels):
|
| 164 |
+
self.indices_inverse[self.indices[i]] = i
|
| 165 |
+
if shuffle:
|
| 166 |
+
self.reset_indices()
|
| 167 |
+
|
| 168 |
+
def reset_indices(self):
|
| 169 |
+
shuffle_idx = torch.randperm(self.indices.shape[0])
|
| 170 |
+
self.indices = self.indices[shuffle_idx]
|
| 171 |
+
for i in range(self.num_channels):
|
| 172 |
+
self.indices_inverse[self.indices[i]] = i
|
| 173 |
+
|
| 174 |
+
def forward(self, input, reverse=False):
|
| 175 |
+
assert len(input.size()) == 4
|
| 176 |
+
if not reverse:
|
| 177 |
+
input = input[:, self.indices, :, :]
|
| 178 |
+
return input
|
| 179 |
+
else:
|
| 180 |
+
return input[:, self.indices_inverse, :, :]
|
| 181 |
+
|
| 182 |
+
class Split2d(nn.Module):
|
| 183 |
+
|
| 184 |
+
def __init__(self, num_channels):
|
| 185 |
+
super().__init__()
|
| 186 |
+
self.conv = Conv2dZeros(num_channels // 2, num_channels)
|
| 187 |
+
|
| 188 |
+
def split2d_prior(self, z):
|
| 189 |
+
h = self.conv(z)
|
| 190 |
+
return split_feature(h, 'cross')
|
| 191 |
+
|
| 192 |
+
def forward(self, input, logdet=0.0, reverse=False, temperature=None):
|
| 193 |
+
if reverse:
|
| 194 |
+
z1 = input
|
| 195 |
+
(mean, logs) = self.split2d_prior(z1)
|
| 196 |
+
z2 = gaussian_sample(mean, logs, temperature)
|
| 197 |
+
z = torch.cat((z1, z2), dim=1)
|
| 198 |
+
return (z, logdet)
|
| 199 |
+
else:
|
| 200 |
+
(z1, z2) = split_feature(input, 'split')
|
| 201 |
+
(mean, logs) = self.split2d_prior(z1)
|
| 202 |
+
logdet = gaussian_likelihood(mean, logs, z2) + logdet
|
| 203 |
+
return (z1, logdet)
|
| 204 |
+
|
| 205 |
+
class SqueezeLayer(nn.Module):
|
| 206 |
+
|
| 207 |
+
def __init__(self, factor):
|
| 208 |
+
super().__init__()
|
| 209 |
+
self.factor = factor
|
| 210 |
+
|
| 211 |
+
def forward(self, input, logdet=None, reverse=False):
|
| 212 |
+
if reverse:
|
| 213 |
+
output = unsqueeze2d(input, self.factor)
|
| 214 |
+
else:
|
| 215 |
+
output = squeeze2d(input, self.factor)
|
| 216 |
+
return (output, logdet)
|
| 217 |
+
|
| 218 |
+
class InvertibleConv1x1(nn.Module):
|
| 219 |
+
|
| 220 |
+
def __init__(self, num_channels, LU_decomposed):
|
| 221 |
+
super().__init__()
|
| 222 |
+
w_shape = [num_channels, num_channels]
|
| 223 |
+
w_init = torch.linalg.qr(torch.randn(*w_shape))[0]
|
| 224 |
+
if not LU_decomposed:
|
| 225 |
+
self.weight = nn.Parameter(torch.Tensor(w_init))
|
| 226 |
+
else:
|
| 227 |
+
(p, lower, upper) = torch.lu_unpack(*torch.lu(w_init))
|
| 228 |
+
s = torch.diag(upper)
|
| 229 |
+
sign_s = torch.sign(s)
|
| 230 |
+
log_s = torch.log(torch.abs(s))
|
| 231 |
+
upper = torch.triu(upper, 1)
|
| 232 |
+
l_mask = torch.tril(torch.ones(w_shape), -1)
|
| 233 |
+
eye = torch.eye(*w_shape)
|
| 234 |
+
self.register_buffer('p', p)
|
| 235 |
+
self.register_buffer('sign_s', sign_s)
|
| 236 |
+
self.lower = nn.Parameter(lower)
|
| 237 |
+
self.log_s = nn.Parameter(log_s)
|
| 238 |
+
self.upper = nn.Parameter(upper)
|
| 239 |
+
self.l_mask = l_mask
|
| 240 |
+
self.eye = eye
|
| 241 |
+
self.w_shape = w_shape
|
| 242 |
+
self.LU_decomposed = LU_decomposed
|
| 243 |
+
|
| 244 |
+
def get_weight(self, input, reverse):
|
| 245 |
+
(b, c, h, w) = input.shape
|
| 246 |
+
if not self.LU_decomposed:
|
| 247 |
+
dlogdet = torch.slogdet(self.weight)[1] * h * w
|
| 248 |
+
if reverse:
|
| 249 |
+
weight = torch.inverse(self.weight)
|
| 250 |
+
else:
|
| 251 |
+
weight = self.weight
|
| 252 |
+
else:
|
| 253 |
+
self.l_mask = self.l_mask.to(input.device)
|
| 254 |
+
self.eye = self.eye.to(input.device)
|
| 255 |
+
lower = self.lower * self.l_mask + self.eye
|
| 256 |
+
u = self.upper * self.l_mask.transpose(0, 1).contiguous()
|
| 257 |
+
u += torch.diag(self.sign_s * torch.exp(self.log_s))
|
| 258 |
+
dlogdet = torch.sum(self.log_s) * h * w
|
| 259 |
+
if reverse:
|
| 260 |
+
u_inv = torch.inverse(u)
|
| 261 |
+
l_inv = torch.inverse(lower)
|
| 262 |
+
p_inv = torch.inverse(self.p)
|
| 263 |
+
weight = torch.matmul(u_inv, torch.matmul(l_inv, p_inv))
|
| 264 |
+
else:
|
| 265 |
+
weight = torch.matmul(self.p, torch.matmul(lower, u))
|
| 266 |
+
return (weight.view(self.w_shape[0], self.w_shape[1], 1, 1), dlogdet)
|
| 267 |
+
|
| 268 |
+
def forward(self, input, logdet=None, reverse=False):
|
| 269 |
+
(weight, dlogdet) = self.get_weight(input, reverse)
|
| 270 |
+
if not reverse:
|
| 271 |
+
z = F.conv2d(input, weight)
|
| 272 |
+
if logdet is not None:
|
| 273 |
+
logdet = logdet + dlogdet
|
| 274 |
+
return (z, logdet)
|
| 275 |
+
else:
|
| 276 |
+
z = F.conv2d(input, weight)
|
| 277 |
+
if logdet is not None:
|
| 278 |
+
logdet = logdet - dlogdet
|
| 279 |
+
return (z, logdet)
|
models/HSI_to_RGB/invertible_isp_model/utils.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
def compute_same_pad(kernel_size, stride):
|
| 5 |
+
if isinstance(kernel_size, int):
|
| 6 |
+
kernel_size = [kernel_size]
|
| 7 |
+
if isinstance(stride, int):
|
| 8 |
+
stride = [stride]
|
| 9 |
+
assert len(stride) == len(kernel_size), 'Pass kernel size and stride both as int, or both as equal length iterable'
|
| 10 |
+
return [((k - 1) * s + 1) // 2 for (k, s) in zip(kernel_size, stride)]
|
| 11 |
+
|
| 12 |
+
def uniform_binning_correction(x, n_bits=8):
|
| 13 |
+
(b, c, h, w) = x.size()
|
| 14 |
+
n_bins = 2 ** n_bits
|
| 15 |
+
chw = c * h * w
|
| 16 |
+
x += torch.zeros_like(x).uniform_(0, 1.0 / n_bins)
|
| 17 |
+
objective = -math.log(n_bins) * chw * torch.ones(b, device=x.device)
|
| 18 |
+
return (x, objective)
|
| 19 |
+
|
| 20 |
+
def split_feature(tensor, type='split'):
|
| 21 |
+
C = tensor.size(1)
|
| 22 |
+
if type == 'split':
|
| 23 |
+
return (tensor[:, :1, ...], tensor[:, 1:, ...])
|
| 24 |
+
elif type == 'cross':
|
| 25 |
+
return (tensor[:, 0::2, ...], tensor[:, 1::2, ...])
|
models/HSI_to_RGB/lib_hsi_EVPL.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
import numpy as np
|
| 6 |
+
from .invertible_isp_model.model import InvISPNet
|
| 7 |
+
|
| 8 |
+
# LIB-HSI 数据集波长数组 (204通道, 400-1000nm VNIR范围)
|
| 9 |
+
wavelengths = np.linspace(300, 700, 31)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class EVPL(nn.Module):
|
| 13 |
+
"""
|
| 14 |
+
EVPL (Evolutionary Vision Perception Layer) for LIB-HSI dataset
|
| 15 |
+
|
| 16 |
+
针对建筑立面高光谱数据集优化的视蛋白层模块
|
| 17 |
+
- 204 光谱通道
|
| 18 |
+
- 波长范围: 400-1000nm
|
| 19 |
+
- 可学习的视蛋白波长参数
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
def __init__(self, lamda_max_1, lamda_max_2, lamda_max_3, device, use_isp=False):
|
| 23 |
+
"""
|
| 24 |
+
Args:
|
| 25 |
+
lamda_max_1: 第一个视蛋白的峰值波长 (nm)
|
| 26 |
+
lamda_max_2: 第二个视蛋白的峰值波长 (nm)
|
| 27 |
+
lamda_max_3: 第三个视蛋白的峰值波长 (nm)
|
| 28 |
+
device: 运行设备
|
| 29 |
+
use_isp: 是否使用可逆ISP网络
|
| 30 |
+
"""
|
| 31 |
+
super(EVPL, self).__init__()
|
| 32 |
+
self.filter_spectral_response = Gaussian_kernel_conv2d(
|
| 33 |
+
lamda_max_1, lamda_max_2, lamda_max_3, device
|
| 34 |
+
)
|
| 35 |
+
self.two_to_rgb = nn.Conv2d(2, 3, kernel_size=(1, 1))
|
| 36 |
+
self.use_isp = use_isp
|
| 37 |
+
if use_isp:
|
| 38 |
+
self.InvISPNet = InvISPNet()
|
| 39 |
+
|
| 40 |
+
def forward(self, x):
|
| 41 |
+
x = self.filter_spectral_response(x)
|
| 42 |
+
if self.use_isp:
|
| 43 |
+
x = self.InvISPNet(x)
|
| 44 |
+
else:
|
| 45 |
+
# 输出归一化到 [0, 1] 范围,确保 SegFormer 输入稳定
|
| 46 |
+
# 使用 per-channel min-max normalization
|
| 47 |
+
B, C, H, W = x.shape
|
| 48 |
+
x_flat = x.view(B, C, -1)
|
| 49 |
+
x_min = x_flat.min(dim=2, keepdim=True)[0].unsqueeze(-1)
|
| 50 |
+
x_max = x_flat.max(dim=2, keepdim=True)[0].unsqueeze(-1)
|
| 51 |
+
x = (x - x_min) / (x_max - x_min + 1e-6)
|
| 52 |
+
x = self.two_to_rgb(x)
|
| 53 |
+
return x
|
| 54 |
+
|
| 55 |
+
def get_lambda_max(self):
|
| 56 |
+
"""返回当前学习到的视蛋白波长参数"""
|
| 57 |
+
return {
|
| 58 |
+
'lambda_1': self.filter_spectral_response.lamda_max_1.item(),
|
| 59 |
+
'lambda_2': self.filter_spectral_response.lamda_max_2.item(),
|
| 60 |
+
'lambda_3': self.filter_spectral_response.lamda_max_3.item(),
|
| 61 |
+
'std': self.filter_spectral_response.std, # 固定值
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class Gaussian_kernel_conv2d(nn.Module):
|
| 66 |
+
"""
|
| 67 |
+
高斯核卷积层,模拟视蛋白的光谱响应曲线
|
| 68 |
+
|
| 69 |
+
使用可学习的高斯核将高光谱图像转换为三通道信号
|
| 70 |
+
"""
|
| 71 |
+
|
| 72 |
+
def __init__(self, lamda_max_1, lamda_max_2, lamda_max_3, device, trainable=True):
|
| 73 |
+
"""
|
| 74 |
+
Args:
|
| 75 |
+
lamda_max_1-3: 三个视蛋白的峰值波长
|
| 76 |
+
device: 运行设备
|
| 77 |
+
trainable: 波长参数是否可训练
|
| 78 |
+
"""
|
| 79 |
+
super(Gaussian_kernel_conv2d, self).__init__()
|
| 80 |
+
|
| 81 |
+
# 可学习的波长参数
|
| 82 |
+
self.lamda_max_1 = nn.Parameter(
|
| 83 |
+
torch.tensor(lamda_max_1, device=device, dtype=torch.float32), requires_grad=trainable
|
| 84 |
+
)
|
| 85 |
+
self.lamda_max_2 = nn.Parameter(
|
| 86 |
+
torch.tensor(lamda_max_2, device=device, dtype=torch.float32), requires_grad=trainable
|
| 87 |
+
)
|
| 88 |
+
self.lamda_max_3 = nn.Parameter(
|
| 89 |
+
torch.tensor(lamda_max_3, device=device, dtype=torch.float32), requires_grad=trainable
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
# 波长数组 (204 通道)
|
| 93 |
+
self.register_buffer('wavelengths', torch.tensor(
|
| 94 |
+
wavelengths, dtype=torch.float32
|
| 95 |
+
))
|
| 96 |
+
|
| 97 |
+
# 固定的高斯核标准差 (控制光谱响应带宽)
|
| 98 |
+
# 60nm:对于 400-1000nm 范围,覆盖约 10% 的波长,比之前的 30nm 更宽
|
| 99 |
+
self.std = 20.0
|
| 100 |
+
|
| 101 |
+
self.device = device
|
| 102 |
+
|
| 103 |
+
def forward(self, input):
|
| 104 |
+
"""
|
| 105 |
+
前向传播
|
| 106 |
+
|
| 107 |
+
Args:
|
| 108 |
+
input: 高光谱图像 [B, 204, H, W]
|
| 109 |
+
|
| 110 |
+
Returns:
|
| 111 |
+
output: 三通道输出 [B, 3, H, W]
|
| 112 |
+
"""
|
| 113 |
+
# 动态计算高斯核权重 (支持波长参数的梯度更新)
|
| 114 |
+
kernel_weight_1 = self._gaussian_kernel(self.lamda_max_1)
|
| 115 |
+
kernel_weight_2 = self._gaussian_kernel(self.lamda_max_2)
|
| 116 |
+
# kernel_weight_3 = self._gaussian_kernel(self.lamda_max_3)
|
| 117 |
+
|
| 118 |
+
# 合并为 [3, 204, 1, 1] 的卷积核
|
| 119 |
+
# kernel = torch.cat([kernel_weight_1, kernel_weight_2, kernel_weight_3], dim=0)
|
| 120 |
+
kernel = torch.cat([kernel_weight_1, kernel_weight_2], dim=0)
|
| 121 |
+
|
| 122 |
+
# 应用卷积
|
| 123 |
+
output = F.conv2d(input, kernel)
|
| 124 |
+
|
| 125 |
+
return output
|
| 126 |
+
|
| 127 |
+
def _gaussian_kernel(self, lamda_max):
|
| 128 |
+
"""计算单个高斯核"""
|
| 129 |
+
weight = torch.exp(-((self.wavelengths - lamda_max) ** 2) / (2 * self.std ** 2))
|
| 130 |
+
weight = weight / (weight.sum() + 1e-6)
|
| 131 |
+
return weight.unsqueeze(0).unsqueeze(2).unsqueeze(3)
|
| 132 |
+
|
| 133 |
+
def print_lambda(self):
|
| 134 |
+
"""打印当前波长参数"""
|
| 135 |
+
print(f'lamda_max_1: {self.lamda_max_1.data.item():.2f} nm, '
|
| 136 |
+
f'lamda_max_2: {self.lamda_max_2.data.item():.2f} nm, '
|
| 137 |
+
f'lamda_max_3: {self.lamda_max_3.data.item():.2f} nm, '
|
| 138 |
+
f'std: {self.std:.2f} nm (fixed)')
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
class EVPL_Tetrachromatic(nn.Module):
|
| 142 |
+
"""
|
| 143 |
+
四色视觉 EVPL 模块 (模拟鸟类等四色视觉生物)
|
| 144 |
+
"""
|
| 145 |
+
|
| 146 |
+
def __init__(self, lamda_max_1, lamda_max_2, lamda_max_3, lamda_max_4, device):
|
| 147 |
+
super(EVPL_Tetrachromatic, self).__init__()
|
| 148 |
+
self.filter_spectral_response = Gaussian_kernel_conv2d_4(
|
| 149 |
+
lamda_max_1, lamda_max_2, lamda_max_3, lamda_max_4, device
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
def forward(self, x):
|
| 153 |
+
return self.filter_spectral_response(x)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
class Gaussian_kernel_conv2d_4(nn.Module):
|
| 157 |
+
"""四通道高斯核卷积层"""
|
| 158 |
+
|
| 159 |
+
def __init__(self, lamda_max_1, lamda_max_2, lamda_max_3, lamda_max_4, device, trainable=True):
|
| 160 |
+
super(Gaussian_kernel_conv2d_4, self).__init__()
|
| 161 |
+
|
| 162 |
+
self.lamda_max_1 = nn.Parameter(torch.tensor(lamda_max_1, device=device), requires_grad=trainable)
|
| 163 |
+
self.lamda_max_2 = nn.Parameter(torch.tensor(lamda_max_2, device=device), requires_grad=trainable)
|
| 164 |
+
self.lamda_max_3 = nn.Parameter(torch.tensor(lamda_max_3, device=device), requires_grad=trainable)
|
| 165 |
+
self.lamda_max_4 = nn.Parameter(torch.tensor(lamda_max_4, device=device), requires_grad=trainable)
|
| 166 |
+
|
| 167 |
+
self.wavelengths = torch.tensor(wavelengths, dtype=torch.float32, device=device, requires_grad=True)
|
| 168 |
+
self.std = 10.0
|
| 169 |
+
self.device = device
|
| 170 |
+
|
| 171 |
+
def forward(self, input):
|
| 172 |
+
kernel_weight_1 = self._gaussian_kernel(self.lamda_max_1)
|
| 173 |
+
kernel_weight_2 = self._gaussian_kernel(self.lamda_max_2)
|
| 174 |
+
kernel_weight_3 = self._gaussian_kernel(self.lamda_max_3)
|
| 175 |
+
kernel_weight_4 = self._gaussian_kernel(self.lamda_max_4)
|
| 176 |
+
|
| 177 |
+
kernel = torch.cat([kernel_weight_1, kernel_weight_2, kernel_weight_3, kernel_weight_4], dim=0)
|
| 178 |
+
output = F.conv2d(input, kernel)
|
| 179 |
+
return output
|
| 180 |
+
|
| 181 |
+
def _gaussian_kernel(self, lamda_max):
|
| 182 |
+
weight = (1 / (self.std * (2 * math.pi) ** 0.5) *
|
| 183 |
+
torch.exp(-((self.wavelengths - lamda_max) ** 2) / (2 * self.std ** 2)))
|
| 184 |
+
return weight.unsqueeze(0).unsqueeze(2).unsqueeze(3)
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
if __name__ == "__main__":
|
| 188 |
+
# 测试 EVPL 模块
|
| 189 |
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 190 |
+
|
| 191 |
+
# 人类三色视觉初始化波长 (蓝、绿、红)
|
| 192 |
+
model = EVPL(
|
| 193 |
+
lamda_max_1=450.0, # S锥 (蓝)
|
| 194 |
+
lamda_max_2=530.0, # M锥 (绿)
|
| 195 |
+
lamda_max_3=560.0, # L锥 (红)
|
| 196 |
+
device=device
|
| 197 |
+
)
|
| 198 |
+
model.to(device)
|
| 199 |
+
|
| 200 |
+
# 测试输入
|
| 201 |
+
input = torch.randn((4, 204, 256, 256)).to(device)
|
| 202 |
+
output = model(input)
|
| 203 |
+
print(f"Input shape: {input.shape}")
|
| 204 |
+
print(f"Output shape: {output.shape}")
|
| 205 |
+
print(f"Lambda max values: {model.get_lambda_max()}")
|
models/HSI_to_RGB/mhsi_EVPL.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
import torch.distributed as dist
|
| 6 |
+
import logging
|
| 7 |
+
from .invertible_isp_model.model import InvISPNet
|
| 8 |
+
|
| 9 |
+
class EVPL(nn.Module):
|
| 10 |
+
|
| 11 |
+
def __init__(self, lamda_max_1, lamda_max_2, lamda_max_3, device):
|
| 12 |
+
super(EVPL, self).__init__()
|
| 13 |
+
self.filter_spectral_response = Gaussian_kernel_conv2d(lamda_max_1, lamda_max_2, lamda_max_3, device)
|
| 14 |
+
self.InvISPNet = InvISPNet()
|
| 15 |
+
|
| 16 |
+
def forward(self, x):
|
| 17 |
+
x = self.filter_spectral_response(x)
|
| 18 |
+
return x
|
| 19 |
+
|
| 20 |
+
class Gaussian_kernel_conv2d(nn.Module):
|
| 21 |
+
|
| 22 |
+
def __init__(self, lamda_max_1, lamda_max_2, lamda_max_3, device):
|
| 23 |
+
super(Gaussian_kernel_conv2d, self).__init__()
|
| 24 |
+
self.lamda_max_1 = nn.Parameter(torch.tensor(lamda_max_1, device=device), requires_grad=True)
|
| 25 |
+
self.lamda_max_2 = nn.Parameter(torch.tensor(lamda_max_2, device=device), requires_grad=True)
|
| 26 |
+
self.lamda_max_3 = nn.Parameter(torch.tensor(lamda_max_3, device=device), requires_grad=True)
|
| 27 |
+
wavelengths = torch.linspace(400, 700, steps=60).to(device, non_blocking=True)
|
| 28 |
+
self.register_buffer('wavelengths', torch.tensor(wavelengths, dtype=torch.float32, requires_grad=False))
|
| 29 |
+
self.std = 15.0
|
| 30 |
+
|
| 31 |
+
def forward(self, input):
|
| 32 |
+
std = self.std
|
| 33 |
+
kernel_weight_1 = 1 / (std * (2 * math.pi) ** 0.5) * torch.exp(-(self.wavelengths - self.lamda_max_1) ** 2 / (2 * std ** 2)).unsqueeze(0).unsqueeze(2).unsqueeze(3)
|
| 34 |
+
kernel_weight_2 = 1 / (std * (2 * math.pi) ** 0.5) * torch.exp(-(self.wavelengths - self.lamda_max_2) ** 2 / (2 * std ** 2)).unsqueeze(0).unsqueeze(2).unsqueeze(3)
|
| 35 |
+
kernel_weight_3 = 1 / (std * (2 * math.pi) ** 0.5) * torch.exp(-(self.wavelengths - self.lamda_max_3) ** 2 / (2 * std ** 2)).unsqueeze(0).unsqueeze(2).unsqueeze(3)
|
| 36 |
+
kernel = torch.cat([kernel_weight_1, kernel_weight_2, kernel_weight_3], dim=0)
|
| 37 |
+
output = F.conv2d(input, kernel)
|
| 38 |
+
return output
|
| 39 |
+
if __name__ == '__main__':
|
| 40 |
+
input = torch.randn((4, 129, 400, 400))
|
| 41 |
+
model = Gaussian_kernel_conv2d(20.0, 30.0, 60.0, 90.0)
|
| 42 |
+
output = model(input)
|
| 43 |
+
print(output.shape)
|
models/HSI_to_RGB/mhsi_EVPL_ablation.py
ADDED
|
@@ -0,0 +1,531 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
mhsi_EVPL_ablation.py
|
| 3 |
+
|
| 4 |
+
MHSI 数据集 EVPL 对比实验(消融)模块
|
| 5 |
+
针对 Reviewer Weakness:
|
| 6 |
+
"Missing baselines: comparisons are only against RGB,
|
| 7 |
+
no evaluation of existing band selection or filter optimization methods"
|
| 8 |
+
|
| 9 |
+
数据集参数:
|
| 10 |
+
num_bands = 60
|
| 11 |
+
wavelengths = linspace(400, 1000, 60) 单位 nm
|
| 12 |
+
std (原始固定) = 10.0 nm
|
| 13 |
+
|
| 14 |
+
论证链:
|
| 15 |
+
Band Selection (PCA / SoftBand) ← 无/弱学习
|
| 16 |
+
↓ 差距说明"学习光谱响应有价值"
|
| 17 |
+
Free 1×1 Conv (无形状约束) ← 完全数据驱动
|
| 18 |
+
↓ 差距说明"高斯形状约束有价值"
|
| 19 |
+
Gaussian Unconstrained ← 可训练高斯,无范围/间隔约束
|
| 20 |
+
↓ 差距说明"固定先验 λ_max 是否本身就足够"
|
| 21 |
+
EVPL (固定 λ_max,固定 std) ← 本文方法
|
| 22 |
+
|
| 23 |
+
注意:原始 mhsi_EVPL.EVPL 的 λ_max 是 requires_grad=False(固定),
|
| 24 |
+
GaussianUnconstrained 额外引入"可训练 λ"这一消融维度。
|
| 25 |
+
|
| 26 |
+
训练脚本替换:
|
| 27 |
+
ablation_map = {
|
| 28 |
+
'evpl': lambda: EVPL(20., 30., 60., device),
|
| 29 |
+
'gauss_nocon': lambda: EVPL_GaussianUnconstrained(device),
|
| 30 |
+
'free': lambda: EVPL_FreeConv(device),
|
| 31 |
+
'pca': lambda: EVPL_PCA(device),
|
| 32 |
+
'softband': lambda: EVPL_SoftBandSelection(device),
|
| 33 |
+
}
|
| 34 |
+
model_evpl = ablation_map[args.ablation]()
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
import math
|
| 38 |
+
import torch
|
| 39 |
+
import torch.nn as nn
|
| 40 |
+
import torch.nn.functional as F
|
| 41 |
+
import numpy as np
|
| 42 |
+
|
| 43 |
+
try:
|
| 44 |
+
from scipy.optimize import curve_fit
|
| 45 |
+
HAS_SCIPY = True
|
| 46 |
+
except ImportError:
|
| 47 |
+
HAS_SCIPY = False
|
| 48 |
+
|
| 49 |
+
from .mhsi_EVPL import EVPL
|
| 50 |
+
|
| 51 |
+
# MHSI 数据集参数
|
| 52 |
+
NUM_BANDS = 60
|
| 53 |
+
SPECTRAL_RANGE = (400, 1000)
|
| 54 |
+
_WAVELENGTHS_NP = np.linspace(400, 1000, NUM_BANDS)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
# ====================================================================
|
| 58 |
+
# FreeSpectralConv(内部辅助,供 EVPL_FreeConv 使用)
|
| 59 |
+
# ====================================================================
|
| 60 |
+
|
| 61 |
+
class _FreeSpectralConv(nn.Module):
|
| 62 |
+
def __init__(self, device, num_bands=NUM_BANDS, spectral_range=SPECTRAL_RANGE,
|
| 63 |
+
out_channels=3, use_softplus=True):
|
| 64 |
+
super().__init__()
|
| 65 |
+
self.num_bands = num_bands
|
| 66 |
+
self.out_channels = out_channels
|
| 67 |
+
self.use_softplus = use_softplus
|
| 68 |
+
self.conv = nn.Conv2d(num_bands, out_channels, kernel_size=1, bias=False)
|
| 69 |
+
wl_np = np.linspace(spectral_range[0], spectral_range[1], num_bands)
|
| 70 |
+
self.register_buffer('wavelengths', torch.tensor(wl_np, dtype=torch.float32))
|
| 71 |
+
|
| 72 |
+
def forward(self, x):
|
| 73 |
+
return self.conv(x)
|
| 74 |
+
|
| 75 |
+
def _get_response(self):
|
| 76 |
+
w = self.conv.weight.squeeze(-1).squeeze(-1)
|
| 77 |
+
return F.softplus(w) if self.use_softplus else w.abs()
|
| 78 |
+
|
| 79 |
+
def get_lambda_peak(self):
|
| 80 |
+
r = self._get_response().detach().cpu()
|
| 81 |
+
wl = self.wavelengths.cpu().numpy()
|
| 82 |
+
return [float(wl[r[c].argmax().item()]) for c in range(self.out_channels)]
|
| 83 |
+
|
| 84 |
+
def get_lambda_centroid(self):
|
| 85 |
+
r = self._get_response().detach()
|
| 86 |
+
wl = self.wavelengths
|
| 87 |
+
return [float(((r[c] * wl).sum() / (r[c].sum() + 1e-8)).item())
|
| 88 |
+
for c in range(self.out_channels)]
|
| 89 |
+
|
| 90 |
+
def get_lambda_gaussian_fit(self):
|
| 91 |
+
if not HAS_SCIPY:
|
| 92 |
+
return None
|
| 93 |
+
r = self._get_response().detach().cpu().numpy()
|
| 94 |
+
wl = self.wavelengths.cpu().numpy()
|
| 95 |
+
centroids = self.get_lambda_centroid()
|
| 96 |
+
|
| 97 |
+
def _gauss(x, amp, mu, sigma):
|
| 98 |
+
return amp * np.exp(-((x - mu) ** 2) / (2 * sigma ** 2))
|
| 99 |
+
|
| 100 |
+
results = []
|
| 101 |
+
for c in range(self.out_channels):
|
| 102 |
+
rc = r[c]
|
| 103 |
+
try:
|
| 104 |
+
popt, _ = curve_fit(
|
| 105 |
+
_gauss, wl, rc,
|
| 106 |
+
p0=[float(rc.max()), centroids[c], 20.0],
|
| 107 |
+
bounds=([0, float(wl.min()), 1.0],
|
| 108 |
+
[np.inf, float(wl.max()), 200.0]),
|
| 109 |
+
maxfev=5000
|
| 110 |
+
)
|
| 111 |
+
r_pred = _gauss(wl, *popt)
|
| 112 |
+
ss_res = np.sum((rc - r_pred) ** 2)
|
| 113 |
+
ss_tot = np.sum((rc - rc.mean()) ** 2) + 1e-10
|
| 114 |
+
results.append({'mu': float(popt[1]), 'sigma': float(abs(popt[2])),
|
| 115 |
+
'r2': float(1.0 - ss_res / ss_tot)})
|
| 116 |
+
except Exception:
|
| 117 |
+
results.append({'mu': centroids[c], 'sigma': float('nan'), 'r2': float('nan')})
|
| 118 |
+
return results
|
| 119 |
+
|
| 120 |
+
def get_spectral_entropy(self):
|
| 121 |
+
r = self._get_response().detach().cpu()
|
| 122 |
+
res = []
|
| 123 |
+
for c in range(self.out_channels):
|
| 124 |
+
p = r[c] / (r[c].sum() + 1e-8)
|
| 125 |
+
res.append(float(-(p * torch.log(p + 1e-10)).sum().item()))
|
| 126 |
+
return res
|
| 127 |
+
|
| 128 |
+
def print_lambda(self):
|
| 129 |
+
peaks = self.get_lambda_peak()
|
| 130 |
+
cents = self.get_lambda_centroid()
|
| 131 |
+
ents = self.get_spectral_entropy()
|
| 132 |
+
fits = self.get_lambda_gaussian_fit()
|
| 133 |
+
for c in range(self.out_channels):
|
| 134 |
+
fit_str = ''
|
| 135 |
+
if fits:
|
| 136 |
+
fit_str = (f", gauss μ={fits[c]['mu']:.2f} σ={fits[c]['sigma']:.2f}"
|
| 137 |
+
f" R²={fits[c]['r2']:.3f}")
|
| 138 |
+
print(f" ch{c+1}: peak={peaks[c]:.2f}nm centroid={cents[c]:.2f}nm"
|
| 139 |
+
f" H={ents[c]:.3f}{fit_str}")
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
# ====================================================================
|
| 143 |
+
# EVPL_GaussianUnconstrained
|
| 144 |
+
# ====================================================================
|
| 145 |
+
|
| 146 |
+
class EVPL_GaussianUnconstrained(nn.Module):
|
| 147 |
+
"""
|
| 148 |
+
Filter Optimization Baseline — 可训练高斯核,无任何约束
|
| 149 |
+
|
| 150 |
+
与原始 EVPL 的消融差异:
|
| 151 |
+
① λ_max 随机初始化(原始使用固定先验且不训练)
|
| 152 |
+
② λ_max requires_grad=True(原始为 False)
|
| 153 |
+
③ std 可训练(原始固定 10.0)
|
| 154 |
+
④ 无范围 clamp、无间隔约束、无排序
|
| 155 |
+
|
| 156 |
+
用于同时验证:固定 λ 先验 和 高斯形状约束 各自的价值。
|
| 157 |
+
"""
|
| 158 |
+
|
| 159 |
+
def __init__(self, device,
|
| 160 |
+
num_bands: int = NUM_BANDS,
|
| 161 |
+
spectral_range: tuple = SPECTRAL_RANGE,
|
| 162 |
+
out_channels: int = 3,
|
| 163 |
+
init_std: float = 10.0,
|
| 164 |
+
random_seed: int = 42):
|
| 165 |
+
super().__init__()
|
| 166 |
+
self.num_bands = num_bands
|
| 167 |
+
self.spectral_range = spectral_range
|
| 168 |
+
self.out_channels = out_channels
|
| 169 |
+
|
| 170 |
+
rng = np.random.RandomState(random_seed)
|
| 171 |
+
init_lambdas = rng.uniform(spectral_range[0], spectral_range[1], out_channels).tolist()
|
| 172 |
+
|
| 173 |
+
self.lamda_max = nn.ParameterList([
|
| 174 |
+
nn.Parameter(torch.tensor(lam, device=device, dtype=torch.float32), requires_grad=True)
|
| 175 |
+
for lam in init_lambdas
|
| 176 |
+
])
|
| 177 |
+
self.log_std = nn.Parameter(
|
| 178 |
+
torch.tensor(math.log(init_std), device=device, dtype=torch.float32),
|
| 179 |
+
requires_grad=True
|
| 180 |
+
)
|
| 181 |
+
wl_np = np.linspace(spectral_range[0], spectral_range[1], num_bands)
|
| 182 |
+
self.register_buffer('wavelengths', torch.tensor(wl_np, dtype=torch.float32))
|
| 183 |
+
|
| 184 |
+
print(f"[EVPL_GaussianUnconstrained/MHSI] init_λ={[f'{l:.1f}' for l in init_lambdas]}, "
|
| 185 |
+
f"init_std={init_std} (可训练,无约束)")
|
| 186 |
+
|
| 187 |
+
def forward(self, x):
|
| 188 |
+
std = torch.exp(self.log_std)
|
| 189 |
+
kernels = []
|
| 190 |
+
for lam in self.lamda_max:
|
| 191 |
+
w = torch.exp(-((self.wavelengths - lam) ** 2) / (2 * std ** 2))
|
| 192 |
+
w = w / (w.sum() + 1e-6)
|
| 193 |
+
kernels.append(w.unsqueeze(0).unsqueeze(2).unsqueeze(3))
|
| 194 |
+
kernel = torch.cat(kernels, dim=0)
|
| 195 |
+
out = F.conv2d(x, kernel)
|
| 196 |
+
B, C, H, W = out.shape
|
| 197 |
+
flat = out.view(B, C, -1)
|
| 198 |
+
out_min = flat.min(dim=2, keepdim=True)[0].unsqueeze(-1)
|
| 199 |
+
out_max = flat.max(dim=2, keepdim=True)[0].unsqueeze(-1)
|
| 200 |
+
return (out - out_min) / (out_max - out_min + 1e-6)
|
| 201 |
+
|
| 202 |
+
def get_lambda_max(self):
|
| 203 |
+
std = float(torch.exp(self.log_std).detach().item())
|
| 204 |
+
result = {'std': std}
|
| 205 |
+
for i, lam in enumerate(self.lamda_max):
|
| 206 |
+
result[f'lambda_{i+1}'] = float(lam.detach().item())
|
| 207 |
+
return result
|
| 208 |
+
|
| 209 |
+
def print_lambda(self):
|
| 210 |
+
info = self.get_lambda_max()
|
| 211 |
+
vals = [f"λ_{i+1}={info[f'lambda_{i+1}']:.2f}" for i in range(self.out_channels)]
|
| 212 |
+
print(f"[EVPL_GaussianUnconstrained/MHSI] {', '.join(vals)}, std={info['std']:.2f} nm")
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
# ====================================================================
|
| 216 |
+
# EVPL_FreeConv
|
| 217 |
+
# ====================================================================
|
| 218 |
+
|
| 219 |
+
class EVPL_FreeConv(nn.Module):
|
| 220 |
+
"""
|
| 221 |
+
Filter Optimization Baseline — 无约束自由 1×1 光谱卷积
|
| 222 |
+
接口与 EVPL 完全一致。
|
| 223 |
+
"""
|
| 224 |
+
|
| 225 |
+
def __init__(self, device,
|
| 226 |
+
num_bands: int = NUM_BANDS,
|
| 227 |
+
spectral_range: tuple = SPECTRAL_RANGE):
|
| 228 |
+
super().__init__()
|
| 229 |
+
self.num_bands = num_bands
|
| 230 |
+
self.spectral_range = spectral_range
|
| 231 |
+
self.filter_spectral_response = _FreeSpectralConv(
|
| 232 |
+
device, num_bands=num_bands, spectral_range=spectral_range, out_channels=3
|
| 233 |
+
)
|
| 234 |
+
print(f"[EVPL_FreeConv/MHSI] num_bands={num_bands}")
|
| 235 |
+
|
| 236 |
+
def forward(self, x):
|
| 237 |
+
out = self.filter_spectral_response(x)
|
| 238 |
+
B, C, H, W = out.shape
|
| 239 |
+
flat = out.view(B, C, -1)
|
| 240 |
+
out_min = flat.min(dim=2, keepdim=True)[0].unsqueeze(-1)
|
| 241 |
+
out_max = flat.max(dim=2, keepdim=True)[0].unsqueeze(-1)
|
| 242 |
+
return (out - out_min) / (out_max - out_min + 1e-6)
|
| 243 |
+
|
| 244 |
+
def get_lambda_max(self):
|
| 245 |
+
fsc = self.filter_spectral_response
|
| 246 |
+
peaks = fsc.get_lambda_peak()
|
| 247 |
+
cents = fsc.get_lambda_centroid()
|
| 248 |
+
ents = fsc.get_spectral_entropy()
|
| 249 |
+
fits = fsc.get_lambda_gaussian_fit()
|
| 250 |
+
n = fsc.out_channels
|
| 251 |
+
result = {}
|
| 252 |
+
for i in range(n):
|
| 253 |
+
result[f'lambda_{i+1}'] = cents[i]
|
| 254 |
+
result[f'lambda_{i+1}_peak'] = peaks[i]
|
| 255 |
+
result[f'entropy_{i+1}'] = ents[i]
|
| 256 |
+
if fits:
|
| 257 |
+
for i, fit in enumerate(fits):
|
| 258 |
+
result[f'gauss_mu_{i+1}'] = fit['mu']
|
| 259 |
+
result[f'gauss_sigma_{i+1}'] = fit['sigma']
|
| 260 |
+
result[f'gauss_r2_{i+1}'] = fit['r2']
|
| 261 |
+
return result
|
| 262 |
+
|
| 263 |
+
def print_lambda(self):
|
| 264 |
+
print("[EVPL_FreeConv/MHSI]")
|
| 265 |
+
self.filter_spectral_response.print_lambda()
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
# ====================================================================
|
| 269 |
+
# EVPL_PCA
|
| 270 |
+
# ====================================================================
|
| 271 |
+
|
| 272 |
+
class EVPL_PCA(nn.Module):
|
| 273 |
+
"""
|
| 274 |
+
Band Selection Baseline — PCA(投影已在 Data_Generate_Bile_PCA 层完成)
|
| 275 |
+
|
| 276 |
+
本模块仅接收已投影的 out_channels 通道输入,
|
| 277 |
+
做通道归一化后输出。参数量 = 0。
|
| 278 |
+
|
| 279 |
+
配套使用:
|
| 280 |
+
from dataloader.Data_Generate import Data_Generate_Bile_PCA
|
| 281 |
+
train_dataset = Data_Generate_Bile_PCA(img_paths, seg_paths, ...)
|
| 282 |
+
# Dataset.__getitem__ 直接返回 [3, H, W] 已投影数据
|
| 283 |
+
evpl_pca = EVPL_PCA(device).to(device)
|
| 284 |
+
"""
|
| 285 |
+
|
| 286 |
+
def __init__(self, device, out_channels: int = 3, **kwargs):
|
| 287 |
+
super().__init__()
|
| 288 |
+
self.out_channels = out_channels
|
| 289 |
+
print(f"[EVPL_PCA/MHSI] 就绪,期望 {out_channels} 通道输入"
|
| 290 |
+
f"(PCA 投影已在 Data_Generate_Bile_PCA 层完成)")
|
| 291 |
+
|
| 292 |
+
def forward(self, x):
|
| 293 |
+
# x: [B, out_channels, H, W] — 已由 Dataset_PCA 层完成 PCA 投影
|
| 294 |
+
B, C, H, W = x.shape
|
| 295 |
+
flat = x.view(B, C, -1)
|
| 296 |
+
out_min = flat.min(dim=2, keepdim=True)[0].unsqueeze(-1)
|
| 297 |
+
out_max = flat.max(dim=2, keepdim=True)[0].unsqueeze(-1)
|
| 298 |
+
return (x - out_min) / (out_max - out_min + 1e-6)
|
| 299 |
+
|
| 300 |
+
def get_lambda_max(self):
|
| 301 |
+
return {f'lambda_{i+1}': float('nan') for i in range(self.out_channels)}
|
| 302 |
+
|
| 303 |
+
def print_lambda(self):
|
| 304 |
+
print("[EVPL_PCA/MHSI] PCA 投影已在 Data_Generate_Bile_PCA 层完成,无模型内等效波长信息")
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
# ====================================================================
|
| 308 |
+
# EVPL_SoftBandSelection
|
| 309 |
+
# ====================================================================
|
| 310 |
+
|
| 311 |
+
class EVPL_SoftBandSelection(nn.Module):
|
| 312 |
+
"""
|
| 313 |
+
Band Selection Baseline — Gumbel-Softmax 可微分波段选择
|
| 314 |
+
推理时 hard argmax → λ_max = wavelengths[argmax(logits)],有明确物理意义。
|
| 315 |
+
每 epoch 结束调用 anneal_temperature()。
|
| 316 |
+
"""
|
| 317 |
+
|
| 318 |
+
def __init__(self, device,
|
| 319 |
+
num_bands: int = NUM_BANDS,
|
| 320 |
+
spectral_range: tuple = SPECTRAL_RANGE,
|
| 321 |
+
out_channels: int = 3,
|
| 322 |
+
init_temperature: float = 1.0,
|
| 323 |
+
min_temperature: float = 0.1,
|
| 324 |
+
anneal_rate: float = 0.003):
|
| 325 |
+
super().__init__()
|
| 326 |
+
self.num_bands = num_bands
|
| 327 |
+
self.out_channels = out_channels
|
| 328 |
+
self.temperature = init_temperature
|
| 329 |
+
self.min_temperature = min_temperature
|
| 330 |
+
self.anneal_rate = anneal_rate
|
| 331 |
+
self.logits = nn.Parameter(
|
| 332 |
+
torch.randn(out_channels, num_bands, device=device, dtype=torch.float32)
|
| 333 |
+
)
|
| 334 |
+
wl_np = np.linspace(spectral_range[0], spectral_range[1], num_bands)
|
| 335 |
+
self.register_buffer('wavelengths', torch.tensor(wl_np, dtype=torch.float32))
|
| 336 |
+
print(f"[EVPL_SoftBandSelection/MHSI] num_bands={num_bands}, T={init_temperature}")
|
| 337 |
+
|
| 338 |
+
def anneal_temperature(self):
|
| 339 |
+
self.temperature = max(self.min_temperature,
|
| 340 |
+
self.temperature * math.exp(-self.anneal_rate))
|
| 341 |
+
|
| 342 |
+
def _get_weights(self):
|
| 343 |
+
if self.training:
|
| 344 |
+
return F.gumbel_softmax(self.logits, tau=self.temperature, hard=False, dim=-1)
|
| 345 |
+
else:
|
| 346 |
+
idx = self.logits.argmax(dim=-1, keepdim=True)
|
| 347 |
+
return torch.zeros_like(self.logits).scatter_(-1, idx, 1.0)
|
| 348 |
+
|
| 349 |
+
def forward(self, x):
|
| 350 |
+
weights = self._get_weights()
|
| 351 |
+
kernel = weights.unsqueeze(-1).unsqueeze(-1)
|
| 352 |
+
out = F.conv2d(x, kernel)
|
| 353 |
+
B, C, H, W = out.shape
|
| 354 |
+
flat = out.view(B, C, -1)
|
| 355 |
+
out_min = flat.min(dim=2, keepdim=True)[0].unsqueeze(-1)
|
| 356 |
+
out_max = flat.max(dim=2, keepdim=True)[0].unsqueeze(-1)
|
| 357 |
+
return (out - out_min) / (out_max - out_min + 1e-6)
|
| 358 |
+
|
| 359 |
+
def get_lambda_max(self):
|
| 360 |
+
wl = self.wavelengths
|
| 361 |
+
hard_idx = self.logits.detach().argmax(dim=-1)
|
| 362 |
+
soft_w = F.softmax(self.logits.detach(), dim=-1)
|
| 363 |
+
result = {'temperature': self.temperature}
|
| 364 |
+
for i in range(self.out_channels):
|
| 365 |
+
result[f'lambda_{i+1}'] = float(wl[hard_idx[i]].item())
|
| 366 |
+
result[f'lambda_{i+1}_soft_centroid'] = float(
|
| 367 |
+
((soft_w[i] * wl).sum() / (soft_w[i].sum() + 1e-8)).item()
|
| 368 |
+
)
|
| 369 |
+
return result
|
| 370 |
+
|
| 371 |
+
def print_lambda(self):
|
| 372 |
+
info = self.get_lambda_max()
|
| 373 |
+
print(f"[EVPL_SoftBandSelection/MHSI] T={info['temperature']:.4f}")
|
| 374 |
+
for i in range(self.out_channels):
|
| 375 |
+
print(f" ch{i+1}: hard λ={info[f'lambda_{i+1}']:.2f} nm "
|
| 376 |
+
f"soft_centroid={info[f'lambda_{i+1}_soft_centroid']:.2f} nm")
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
# ====================================================================
|
| 380 |
+
# compare_all_baselines
|
| 381 |
+
# ====================================================================
|
| 382 |
+
|
| 383 |
+
def compare_all_baselines(models: dict,
|
| 384 |
+
spectral_range: tuple = SPECTRAL_RANGE,
|
| 385 |
+
num_bands: int = NUM_BANDS,
|
| 386 |
+
save_path: str = None) -> dict:
|
| 387 |
+
"""横向对比 MHSI 所有 baseline 的等效 λ_max 与光谱响应。"""
|
| 388 |
+
sep = "=" * 80
|
| 389 |
+
DISPLAY = {
|
| 390 |
+
'evpl': 'EVPL (Fixed Gaussian) [本文]',
|
| 391 |
+
'gauss_nocon': 'Gaussian Unconstrained [消融①]',
|
| 392 |
+
'free': 'Free Spectral Conv [消融②]',
|
| 393 |
+
'pca': 'PCA Projection (fixed) [Band Sel.]',
|
| 394 |
+
'softband': 'Gumbel SoftBand Selection [Band Sel.]',
|
| 395 |
+
}
|
| 396 |
+
print(sep)
|
| 397 |
+
print("MHSI 全基线光谱响应对比")
|
| 398 |
+
print(sep)
|
| 399 |
+
all_info = {}
|
| 400 |
+
for name, model in models.items():
|
| 401 |
+
print(f"\n[{DISPLAY.get(name, name)}]")
|
| 402 |
+
model.print_lambda()
|
| 403 |
+
all_info[name] = model.get_lambda_max()
|
| 404 |
+
|
| 405 |
+
_sample_info = next(iter(all_info.values())) if all_info else {}
|
| 406 |
+
n_ch = max(sum(1 for k in _sample_info if k.startswith('lambda_') and k[7:].isdigit()), 1)
|
| 407 |
+
hdr = ' '.join(f"{'Ch'+str(i+1)+' (nm)':>12}" for i in range(n_ch))
|
| 408 |
+
print(f"\n{'':30s} {hdr}")
|
| 409 |
+
print("-" * (32 + 13 * n_ch))
|
| 410 |
+
for name, info in all_info.items():
|
| 411 |
+
disp = DISPLAY.get(name, name)[:28]
|
| 412 |
+
lams = [info.get(f'lambda_{i+1}', float('nan')) for i in range(n_ch)]
|
| 413 |
+
row = ' '.join(f"{l:12.2f}" for l in lams)
|
| 414 |
+
print(f" {disp:28s} {row}")
|
| 415 |
+
|
| 416 |
+
if save_path is not None:
|
| 417 |
+
try:
|
| 418 |
+
import matplotlib
|
| 419 |
+
matplotlib.use('Agg')
|
| 420 |
+
import matplotlib.pyplot as plt
|
| 421 |
+
wl = np.linspace(spectral_range[0], spectral_range[1], num_bands)
|
| 422 |
+
n_models = len(models)
|
| 423 |
+
_all_colors = ['royalblue', 'seagreen', 'tomato', 'darkorchid',
|
| 424 |
+
'darkorange', 'teal', 'crimson', 'olive']
|
| 425 |
+
ch_colors = _all_colors[:n_ch]
|
| 426 |
+
ch_titles = [f'Ch{i+1}' for i in range(n_ch)]
|
| 427 |
+
fig, axes = plt.subplots(n_models, n_ch, figsize=(5 * n_ch, 3.5 * n_models), sharex=True)
|
| 428 |
+
if n_models == 1:
|
| 429 |
+
axes = axes[np.newaxis, :]
|
| 430 |
+
if n_ch == 1:
|
| 431 |
+
axes = axes[:, np.newaxis]
|
| 432 |
+
for row, (name, model) in enumerate(models.items()):
|
| 433 |
+
resps = _extract_spectral_response(model, wl, num_bands)
|
| 434 |
+
for ch in range(n_ch):
|
| 435 |
+
ax = axes[row, ch]
|
| 436 |
+
if resps[ch] is not None:
|
| 437 |
+
r = resps[ch]
|
| 438 |
+
ax.plot(wl, r / (r.max() + 1e-8), color=ch_colors[ch], linewidth=2)
|
| 439 |
+
lam = all_info[name].get(f'lambda_{ch+1}', None)
|
| 440 |
+
if lam and not np.isnan(lam):
|
| 441 |
+
ax.axvline(lam, color='black', linestyle='--', alpha=0.7,
|
| 442 |
+
label=f'λ={lam:.1f}nm')
|
| 443 |
+
if row == 0:
|
| 444 |
+
ax.set_title(ch_titles[ch], fontsize=10)
|
| 445 |
+
if ch == 0:
|
| 446 |
+
ax.set_ylabel(DISPLAY.get(name, name)[:20], fontsize=8)
|
| 447 |
+
if row == n_models - 1:
|
| 448 |
+
ax.set_xlabel('Wavelength (nm)')
|
| 449 |
+
ax.legend(fontsize=7)
|
| 450 |
+
ax.grid(True, alpha=0.3)
|
| 451 |
+
fig.suptitle('MHSI Spectral Response — All Baselines', fontsize=13)
|
| 452 |
+
plt.tight_layout()
|
| 453 |
+
plt.savefig(save_path, dpi=150, bbox_inches='tight')
|
| 454 |
+
plt.close(fig)
|
| 455 |
+
print(f"\n [图像已保存] {save_path}")
|
| 456 |
+
except ImportError:
|
| 457 |
+
print(" (matplotlib 不可用,跳过可视化)")
|
| 458 |
+
print(sep)
|
| 459 |
+
return all_info
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
def _extract_spectral_response(model, wl, num_bands):
|
| 463 |
+
try:
|
| 464 |
+
if isinstance(model, EVPL):
|
| 465 |
+
fsr = model.filter_spectral_response
|
| 466 |
+
std = fsr.std
|
| 467 |
+
wl_t = fsr.wavelengths
|
| 468 |
+
resps = []
|
| 469 |
+
for lam in [fsr.lamda_max_1, fsr.lamda_max_2, fsr.lamda_max_3]:
|
| 470 |
+
g = torch.exp(-((wl_t - lam) ** 2) / (2 * std ** 2))
|
| 471 |
+
g = g / (g.sum() + 1e-6)
|
| 472 |
+
resps.append(g.detach().cpu().numpy())
|
| 473 |
+
return resps
|
| 474 |
+
elif isinstance(model, EVPL_GaussianUnconstrained):
|
| 475 |
+
std = torch.exp(model.log_std)
|
| 476 |
+
wl_t = model.wavelengths
|
| 477 |
+
resps = []
|
| 478 |
+
for lam in model.lamda_max:
|
| 479 |
+
g = torch.exp(-((wl_t - lam) ** 2) / (2 * std ** 2))
|
| 480 |
+
g = g / (g.sum() + 1e-6)
|
| 481 |
+
resps.append(g.detach().cpu().numpy())
|
| 482 |
+
return resps
|
| 483 |
+
elif isinstance(model, EVPL_FreeConv):
|
| 484 |
+
r = model.filter_spectral_response._get_response()
|
| 485 |
+
n = model.filter_spectral_response.out_channels
|
| 486 |
+
return [r[j].detach().cpu().numpy() for j in range(n)]
|
| 487 |
+
elif isinstance(model, EVPL_PCA):
|
| 488 |
+
return [None, None, None] # 投影在数据集层,无模型内光谱响应
|
| 489 |
+
elif isinstance(model, EVPL_SoftBandSelection):
|
| 490 |
+
soft_w = F.softmax(model.logits.detach(), dim=-1)
|
| 491 |
+
return [soft_w[j].cpu().numpy() for j in range(model.out_channels)]
|
| 492 |
+
except Exception:
|
| 493 |
+
pass
|
| 494 |
+
return [None, None, None]
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
# ====================================================================
|
| 498 |
+
# 快速测试入口
|
| 499 |
+
# ====================================================================
|
| 500 |
+
|
| 501 |
+
if __name__ == "__main__":
|
| 502 |
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 503 |
+
print(f"device: {device}\n")
|
| 504 |
+
|
| 505 |
+
evpl = EVPL(450.0, 530.0, 580.0, device)
|
| 506 |
+
|
| 507 |
+
gauss_nocon = EVPL_GaussianUnconstrained(device)
|
| 508 |
+
free_conv = EVPL_FreeConv(device)
|
| 509 |
+
# PCA 投影在 Data_Generate_Bile_PCA 层完成,模型不需要投影矩阵
|
| 510 |
+
pca_model = EVPL_PCA(device)
|
| 511 |
+
softband = EVPL_SoftBandSelection(device)
|
| 512 |
+
|
| 513 |
+
models = {
|
| 514 |
+
'evpl': evpl, 'gauss_nocon': gauss_nocon,
|
| 515 |
+
'free': free_conv, 'pca': pca_model, 'softband': softband,
|
| 516 |
+
}
|
| 517 |
+
|
| 518 |
+
print("[前向形状验证]")
|
| 519 |
+
x = torch.randn(2, NUM_BANDS, 64, 64).to(device)
|
| 520 |
+
x_pca = torch.randn(2, 3, 64, 64).to(device) # PCA 已在 Data_Generate_Bile_PCA 层完成
|
| 521 |
+
for name, m in models.items():
|
| 522 |
+
x_in = x_pca if name == 'pca' else x
|
| 523 |
+
out = m(x_in)
|
| 524 |
+
print(f" {name:14s}: {tuple(x_in.shape)} → {tuple(out.shape)}")
|
| 525 |
+
|
| 526 |
+
print("\n[参数量]")
|
| 527 |
+
for name, m in models.items():
|
| 528 |
+
n = sum(p.numel() for p in m.parameters() if p.requires_grad)
|
| 529 |
+
print(f" {name:14s}: {n:6,}")
|
| 530 |
+
|
| 531 |
+
compare_all_baselines(models, save_path="ablation_mhsi_baselines_init.png")
|
models/HSI_to_RGB/minneapple_EVPL.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
from .invertible_isp_model.model import InvISPNet
|
| 6 |
+
|
| 7 |
+
class EVPL(nn.Module):
|
| 8 |
+
|
| 9 |
+
def __init__(self, lamda_max_1, lamda_max_2, lamda_max_3, device, num_channels=129, use_isp=True):
|
| 10 |
+
super(EVPL, self).__init__()
|
| 11 |
+
self.filter_spectral_response = Gaussian_kernel_conv2d(lamda_max_1, lamda_max_2, lamda_max_3, device, num_channels)
|
| 12 |
+
self.use_isp = use_isp
|
| 13 |
+
if use_isp:
|
| 14 |
+
self.InvISPNet = InvISPNet()
|
| 15 |
+
|
| 16 |
+
def forward(self, x):
|
| 17 |
+
x = self.filter_spectral_response(x)
|
| 18 |
+
if self.use_isp:
|
| 19 |
+
x = torch.clamp(x, 0, 1)
|
| 20 |
+
x = self.InvISPNet(x)
|
| 21 |
+
if torch.isnan(x).any():
|
| 22 |
+
print('Warning: InvISPNet output contains NaN!')
|
| 23 |
+
x = torch.nan_to_num(x, nan=0.0)
|
| 24 |
+
return x
|
| 25 |
+
|
| 26 |
+
class Gaussian_kernel_conv2d(nn.Module):
|
| 27 |
+
|
| 28 |
+
def __init__(self, lamda_max_1, lamda_max_2, lamda_max_3, device, num_channels=129):
|
| 29 |
+
super(Gaussian_kernel_conv2d, self).__init__()
|
| 30 |
+
self.num_channels = num_channels
|
| 31 |
+
self.device = device
|
| 32 |
+
self.lamda_max_1 = nn.Parameter(torch.tensor(lamda_max_1, device=device), requires_grad=False)
|
| 33 |
+
self.lamda_max_2 = nn.Parameter(torch.tensor(lamda_max_2, device=device), requires_grad=False)
|
| 34 |
+
self.lamda_max_3 = nn.Parameter(torch.tensor(lamda_max_3, device=device), requires_grad=False)
|
| 35 |
+
self.std = 9.0
|
| 36 |
+
self.register_buffer('x', torch.linspace(400, 1000, steps=num_channels))
|
| 37 |
+
|
| 38 |
+
def forward(self, input):
|
| 39 |
+
if torch.isnan(input).any():
|
| 40 |
+
print('Warning: Input contains NaN!')
|
| 41 |
+
input = torch.nan_to_num(input, nan=0.0)
|
| 42 |
+
std = self.std
|
| 43 |
+
x = self.x
|
| 44 |
+
kernel_weight_1 = 1 / (std * (2 * math.pi) ** 0.5) * torch.exp(-(x - self.lamda_max_1) ** 2 / (2 * std ** 2)).unsqueeze(0).unsqueeze(2).unsqueeze(3)
|
| 45 |
+
kernel_weight_2 = 1 / (std * (2 * math.pi) ** 0.5) * torch.exp(-(x - self.lamda_max_2) ** 2 / (2 * std ** 2)).unsqueeze(0).unsqueeze(2).unsqueeze(3)
|
| 46 |
+
kernel_weight_3 = 1 / (std * (2 * math.pi) ** 0.5) * torch.exp(-(x - self.lamda_max_3) ** 2 / (2 * std ** 2)).unsqueeze(0).unsqueeze(2).unsqueeze(3)
|
| 47 |
+
kernel = torch.cat([kernel_weight_1, kernel_weight_2, kernel_weight_3], dim=0)
|
| 48 |
+
output = F.conv2d(input, kernel)
|
| 49 |
+
if torch.isnan(output).any():
|
| 50 |
+
print('Warning: Output contains NaN after conv!')
|
| 51 |
+
output = torch.nan_to_num(output, nan=0.0)
|
| 52 |
+
return output
|
| 53 |
+
|
| 54 |
+
class EVPLPassthrough(nn.Module):
|
| 55 |
+
|
| 56 |
+
def __init__(self, device=None):
|
| 57 |
+
super(EVPLPassthrough, self).__init__()
|
| 58 |
+
|
| 59 |
+
def forward(self, x):
|
| 60 |
+
return x
|
| 61 |
+
|
| 62 |
+
class EVPLWithNormalization(nn.Module):
|
| 63 |
+
|
| 64 |
+
def __init__(self, lamda_max_1, lamda_max_2, lamda_max_3, device, num_channels=129, use_isp=True):
|
| 65 |
+
super(EVPLWithNormalization, self).__init__()
|
| 66 |
+
self.evpl = EVPL(lamda_max_1, lamda_max_2, lamda_max_3, device, num_channels, use_isp)
|
| 67 |
+
self.register_buffer('mean', torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1))
|
| 68 |
+
self.register_buffer('std', torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1))
|
| 69 |
+
|
| 70 |
+
def forward(self, x):
|
| 71 |
+
out = self.evpl(x)
|
| 72 |
+
out = (out - self.mean.to(out.device)) / self.std.to(out.device)
|
| 73 |
+
return out
|
| 74 |
+
|
| 75 |
+
class ColorBlindEVPL(nn.Module):
|
| 76 |
+
|
| 77 |
+
def __init__(self, blindness_type='protanopia', device=None):
|
| 78 |
+
super(ColorBlindEVPL, self).__init__()
|
| 79 |
+
self.blindness_type = blindness_type
|
| 80 |
+
matrices = {'protanopia': torch.tensor([[0.567, 0.433, 0.0], [0.558, 0.442, 0.0], [0.0, 0.242, 0.758]]), 'deuteranopia': torch.tensor([[0.625, 0.375, 0.0], [0.7, 0.3, 0.0], [0.0, 0.3, 0.7]]), 'tritanopia': torch.tensor([[0.95, 0.05, 0.0], [0.0, 0.433, 0.567], [0.0, 0.475, 0.525]]), 'monochromacy': torch.tensor([[0.299, 0.587, 0.114], [0.299, 0.587, 0.114], [0.299, 0.587, 0.114]])}
|
| 81 |
+
if blindness_type in matrices:
|
| 82 |
+
self.register_buffer('transform_matrix', matrices[blindness_type].float())
|
| 83 |
+
else:
|
| 84 |
+
self.register_buffer('transform_matrix', torch.eye(3).float())
|
| 85 |
+
self.register_buffer('mean', torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1))
|
| 86 |
+
self.register_buffer('std', torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1))
|
| 87 |
+
|
| 88 |
+
def forward(self, x):
|
| 89 |
+
(B, C, H, W) = x.shape
|
| 90 |
+
x_flat = x.view(B, C, -1)
|
| 91 |
+
x_flat = x_flat.permute(0, 2, 1)
|
| 92 |
+
x_transformed = torch.matmul(x_flat, self.transform_matrix.T.to(x.device))
|
| 93 |
+
x_transformed = x_transformed.permute(0, 2, 1)
|
| 94 |
+
out = x_transformed.view(B, C, H, W)
|
| 95 |
+
out = torch.clamp(out, 0, 1)
|
| 96 |
+
out = (out - self.mean.to(out.device)) / self.std.to(out.device)
|
| 97 |
+
return out
|
models/HSI_to_RGB/modid_EVPL.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
import torch.distributed as dist
|
| 6 |
+
import numpy as np
|
| 7 |
+
import logging
|
| 8 |
+
from .invertible_isp_model.model import InvISPNet
|
| 9 |
+
wavelengths = np.array([460.48099, 465.215098, 474.1194, 482.578653, 492.59933, 504.367465, 512.469275, 521.987657, 533.930667, 541.203169, 551.996143, 559.719978, 570.1331, 579.729623, 585.387574, 595.018809])
|
| 10 |
+
|
| 11 |
+
class EVPL(nn.Module):
|
| 12 |
+
|
| 13 |
+
def __init__(self, lamda_max_1, lamda_max_2, lamda_max_3, device):
|
| 14 |
+
super(EVPL, self).__init__()
|
| 15 |
+
self.filter_spectral_response = Gaussian_kernel_conv2d(lamda_max_1, lamda_max_2, lamda_max_3, device)
|
| 16 |
+
self.multi_to_rgb = nn.Conv2d(3, 3, kernel_size=(1, 1))
|
| 17 |
+
self.InvISPNet = InvISPNet()
|
| 18 |
+
|
| 19 |
+
def forward(self, x):
|
| 20 |
+
x = self.filter_spectral_response(x)
|
| 21 |
+
return x
|
| 22 |
+
|
| 23 |
+
class Gaussian_kernel_conv2d(nn.Module):
|
| 24 |
+
|
| 25 |
+
def __init__(self, lamda_max_1, lamda_max_2, lamda_max_3, device):
|
| 26 |
+
super(Gaussian_kernel_conv2d, self).__init__()
|
| 27 |
+
self.lamda_max_1 = nn.Parameter(torch.tensor(lamda_max_1, device=device), requires_grad=True)
|
| 28 |
+
self.lamda_max_2 = nn.Parameter(torch.tensor(lamda_max_2, device=device), requires_grad=True)
|
| 29 |
+
self.lamda_max_3 = nn.Parameter(torch.tensor(lamda_max_3, device=device), requires_grad=True)
|
| 30 |
+
self.register_buffer('wavelengths', torch.tensor(wavelengths, dtype=torch.float32))
|
| 31 |
+
self.std = 70.0
|
| 32 |
+
|
| 33 |
+
def forward(self, input):
|
| 34 |
+
std = self.std
|
| 35 |
+
kernel_weight_1 = 1 / (std * (2 * math.pi) ** 0.5) * torch.exp(-(self.wavelengths - self.lamda_max_1) ** 2 / (2 * std ** 2)).unsqueeze(0).unsqueeze(2).unsqueeze(3)
|
| 36 |
+
kernel_weight_2 = 1 / (std * (2 * math.pi) ** 0.5) * torch.exp(-(self.wavelengths - self.lamda_max_2) ** 2 / (2 * std ** 2)).unsqueeze(0).unsqueeze(2).unsqueeze(3)
|
| 37 |
+
kernel_weight_3 = 1 / (std * (2 * math.pi) ** 0.5) * torch.exp(-(self.wavelengths - self.lamda_max_3) ** 2 / (2 * std ** 2)).unsqueeze(0).unsqueeze(2).unsqueeze(3)
|
| 38 |
+
kernel = torch.cat([kernel_weight_1, kernel_weight_2, kernel_weight_3], dim=0)
|
| 39 |
+
output = F.conv2d(input, kernel)
|
| 40 |
+
return output
|
| 41 |
+
if __name__ == '__main__':
|
| 42 |
+
input = torch.randn((4, 129, 400, 400))
|
| 43 |
+
model = Gaussian_kernel_conv2d(20.0, 30.0, 60.0, 90.0)
|
| 44 |
+
output = model(input)
|
| 45 |
+
print(output.shape)
|
models/HSI_to_RGB/modid_EVPL_ablation.py
ADDED
|
@@ -0,0 +1,539 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
modid_EVPL_ablation.py
|
| 3 |
+
|
| 4 |
+
MODID 数据集 EVPL 对比实验(消融)模块
|
| 5 |
+
针对 Reviewer Weakness:
|
| 6 |
+
"Missing baselines: comparisons are only against RGB,
|
| 7 |
+
no evaluation of existing band selection or filter optimization methods"
|
| 8 |
+
|
| 9 |
+
数据集参数:
|
| 10 |
+
num_bands = 16
|
| 11 |
+
wavelengths = [460.48, 465.22, 474.12, 482.58, 492.60, 504.37,
|
| 12 |
+
512.47, 521.99, 533.93, 541.20, 551.99, 559.72,
|
| 13 |
+
570.13, 579.73, 585.39, 595.02] 单位 nm
|
| 14 |
+
std (原始固定) = 70.0 nm(波长范围窄~135nm,宽 std 保证充分覆盖)
|
| 15 |
+
|
| 16 |
+
论证链:
|
| 17 |
+
Band Selection (PCA / SoftBand) ← 无/弱学习
|
| 18 |
+
↓ 差距说明"学习光谱响应有价值"
|
| 19 |
+
Free 1×1 Conv (无形状约束) ← 完全数据驱动
|
| 20 |
+
↓ 差距说明"高斯形状约束有价值"
|
| 21 |
+
Gaussian Unconstrained ← 可训练高斯,无范围/间隔约束
|
| 22 |
+
↓ 差距说明"固定 λ 先验 + 宽 std 是否已足够"
|
| 23 |
+
EVPL (固定 λ_max,固定 std=70) ← 本文方法
|
| 24 |
+
|
| 25 |
+
注意:原始 modid_EVPL.EVPL 的 λ_max 是 requires_grad=False,
|
| 26 |
+
GaussianUnconstrained 额外引入"可训练 λ"这一消融维度。
|
| 27 |
+
由于 MODID 波段仅 16 个、范围窄(135nm),
|
| 28 |
+
FreeConv 参数量仅 3×16=48,远少于一般数据集,过拟合风险较低。
|
| 29 |
+
|
| 30 |
+
训练脚本替换:
|
| 31 |
+
ablation_map = {
|
| 32 |
+
'evpl': lambda: EVPL(490., 540., 570., device),
|
| 33 |
+
'gauss_nocon': lambda: EVPL_GaussianUnconstrained(device),
|
| 34 |
+
'free': lambda: EVPL_FreeConv(device),
|
| 35 |
+
'pca': lambda: EVPL_PCA(device),
|
| 36 |
+
'softband': lambda: EVPL_SoftBandSelection(device),
|
| 37 |
+
}
|
| 38 |
+
model_evpl = ablation_map[args.ablation]()
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
import math
|
| 42 |
+
import torch
|
| 43 |
+
import torch.nn as nn
|
| 44 |
+
import torch.nn.functional as F
|
| 45 |
+
import numpy as np
|
| 46 |
+
|
| 47 |
+
try:
|
| 48 |
+
from scipy.optimize import curve_fit
|
| 49 |
+
HAS_SCIPY = True
|
| 50 |
+
except ImportError:
|
| 51 |
+
HAS_SCIPY = False
|
| 52 |
+
|
| 53 |
+
from .modid_EVPL import EVPL
|
| 54 |
+
|
| 55 |
+
# MODID 数据集参数(16个不均匀波段)
|
| 56 |
+
NUM_BANDS = 16
|
| 57 |
+
_WAVELENGTHS_NP = np.array([
|
| 58 |
+
460.480990, 465.215098, 474.119400, 482.578653, 492.599330, 504.367465,
|
| 59 |
+
512.469275, 521.987657, 533.930667, 541.203169, 551.996143, 559.719978,
|
| 60 |
+
570.133100, 579.729623, 585.387574, 595.018809
|
| 61 |
+
], dtype=np.float32)
|
| 62 |
+
SPECTRAL_RANGE = (float(_WAVELENGTHS_NP.min()), float(_WAVELENGTHS_NP.max()))
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
# ====================================================================
|
| 66 |
+
# FreeSpectralConv(内部辅助)
|
| 67 |
+
# ====================================================================
|
| 68 |
+
|
| 69 |
+
class _FreeSpectralConv(nn.Module):
|
| 70 |
+
def __init__(self, device, num_bands=NUM_BANDS, wl_np=_WAVELENGTHS_NP,
|
| 71 |
+
out_channels=3, use_softplus=True):
|
| 72 |
+
super().__init__()
|
| 73 |
+
self.num_bands = num_bands
|
| 74 |
+
self.out_channels = out_channels
|
| 75 |
+
self.use_softplus = use_softplus
|
| 76 |
+
self.conv = nn.Conv2d(num_bands, out_channels, kernel_size=1, bias=False)
|
| 77 |
+
self.register_buffer('wavelengths', torch.tensor(wl_np, dtype=torch.float32))
|
| 78 |
+
|
| 79 |
+
def forward(self, x):
|
| 80 |
+
return self.conv(x)
|
| 81 |
+
|
| 82 |
+
def _get_response(self):
|
| 83 |
+
w = self.conv.weight.squeeze(-1).squeeze(-1)
|
| 84 |
+
return F.softplus(w) if self.use_softplus else w.abs()
|
| 85 |
+
|
| 86 |
+
def get_lambda_peak(self):
|
| 87 |
+
r = self._get_response().detach().cpu()
|
| 88 |
+
wl = self.wavelengths.cpu().numpy()
|
| 89 |
+
return [float(wl[r[c].argmax().item()]) for c in range(self.out_channels)]
|
| 90 |
+
|
| 91 |
+
def get_lambda_centroid(self):
|
| 92 |
+
r = self._get_response().detach()
|
| 93 |
+
wl = self.wavelengths
|
| 94 |
+
return [float(((r[c] * wl).sum() / (r[c].sum() + 1e-8)).item())
|
| 95 |
+
for c in range(self.out_channels)]
|
| 96 |
+
|
| 97 |
+
def get_lambda_gaussian_fit(self):
|
| 98 |
+
if not HAS_SCIPY:
|
| 99 |
+
return None
|
| 100 |
+
r = self._get_response().detach().cpu().numpy()
|
| 101 |
+
wl = self.wavelengths.cpu().numpy()
|
| 102 |
+
centroids = self.get_lambda_centroid()
|
| 103 |
+
|
| 104 |
+
def _gauss(x, amp, mu, sigma):
|
| 105 |
+
return amp * np.exp(-((x - mu) ** 2) / (2 * sigma ** 2))
|
| 106 |
+
|
| 107 |
+
results = []
|
| 108 |
+
for c in range(self.out_channels):
|
| 109 |
+
rc = r[c]
|
| 110 |
+
try:
|
| 111 |
+
popt, _ = curve_fit(
|
| 112 |
+
_gauss, wl, rc,
|
| 113 |
+
p0=[float(rc.max()), centroids[c], 20.0],
|
| 114 |
+
bounds=([0, float(wl.min()) - 5, 1.0],
|
| 115 |
+
[np.inf, float(wl.max()) + 5, 200.0]),
|
| 116 |
+
maxfev=5000
|
| 117 |
+
)
|
| 118 |
+
r_pred = _gauss(wl, *popt)
|
| 119 |
+
ss_res = np.sum((rc - r_pred) ** 2)
|
| 120 |
+
ss_tot = np.sum((rc - rc.mean()) ** 2) + 1e-10
|
| 121 |
+
results.append({'mu': float(popt[1]), 'sigma': float(abs(popt[2])),
|
| 122 |
+
'r2': float(1.0 - ss_res / ss_tot)})
|
| 123 |
+
except Exception:
|
| 124 |
+
results.append({'mu': centroids[c], 'sigma': float('nan'), 'r2': float('nan')})
|
| 125 |
+
return results
|
| 126 |
+
|
| 127 |
+
def get_spectral_entropy(self):
|
| 128 |
+
r = self._get_response().detach().cpu()
|
| 129 |
+
res = []
|
| 130 |
+
for c in range(self.out_channels):
|
| 131 |
+
p = r[c] / (r[c].sum() + 1e-8)
|
| 132 |
+
res.append(float(-(p * torch.log(p + 1e-10)).sum().item()))
|
| 133 |
+
return res
|
| 134 |
+
|
| 135 |
+
def print_lambda(self):
|
| 136 |
+
peaks = self.get_lambda_peak()
|
| 137 |
+
cents = self.get_lambda_centroid()
|
| 138 |
+
ents = self.get_spectral_entropy()
|
| 139 |
+
fits = self.get_lambda_gaussian_fit()
|
| 140 |
+
for c in range(self.out_channels):
|
| 141 |
+
fit_str = ''
|
| 142 |
+
if fits:
|
| 143 |
+
fit_str = (f", gauss μ={fits[c]['mu']:.2f} σ={fits[c]['sigma']:.2f}"
|
| 144 |
+
f" R²={fits[c]['r2']:.3f}")
|
| 145 |
+
print(f" ch{c+1}: peak={peaks[c]:.2f}nm centroid={cents[c]:.2f}nm"
|
| 146 |
+
f" H={ents[c]:.3f}{fit_str}")
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
# ====================================================================
|
| 150 |
+
# EVPL_GaussianUnconstrained
|
| 151 |
+
# ====================================================================
|
| 152 |
+
|
| 153 |
+
class EVPL_GaussianUnconstrained(nn.Module):
|
| 154 |
+
"""
|
| 155 |
+
Filter Optimization Baseline — 可训练高斯核,无任何约束
|
| 156 |
+
|
| 157 |
+
与原始 EVPL 的消融差异:
|
| 158 |
+
① λ_max 随机初始化(原始使用固定先验且不训练)
|
| 159 |
+
② λ_max requires_grad=True(原始为 False)
|
| 160 |
+
③ std 可训练(原始固定 70.0)
|
| 161 |
+
④ 无范围 clamp、无间隔约束
|
| 162 |
+
|
| 163 |
+
注意:MODID 波段范围仅约 135nm(460-595nm),
|
| 164 |
+
std 初始化为 20.0 以体现窄范围特性;
|
| 165 |
+
原始固定 std=70.0 几乎覆盖全部波段,此处解除该约束。
|
| 166 |
+
"""
|
| 167 |
+
|
| 168 |
+
def __init__(self, device,
|
| 169 |
+
num_bands: int = NUM_BANDS,
|
| 170 |
+
wl_np: np.ndarray = _WAVELENGTHS_NP,
|
| 171 |
+
out_channels: int = 3,
|
| 172 |
+
init_std: float = 20.0,
|
| 173 |
+
random_seed: int = 42):
|
| 174 |
+
super().__init__()
|
| 175 |
+
self.num_bands = num_bands
|
| 176 |
+
self.out_channels = out_channels
|
| 177 |
+
|
| 178 |
+
rng = np.random.RandomState(random_seed)
|
| 179 |
+
init_lambdas = rng.uniform(float(wl_np.min()), float(wl_np.max()), out_channels).tolist()
|
| 180 |
+
|
| 181 |
+
self.lamda_max = nn.ParameterList([
|
| 182 |
+
nn.Parameter(torch.tensor(lam, device=device, dtype=torch.float32), requires_grad=True)
|
| 183 |
+
for lam in init_lambdas
|
| 184 |
+
])
|
| 185 |
+
self.log_std = nn.Parameter(
|
| 186 |
+
torch.tensor(math.log(init_std), device=device, dtype=torch.float32),
|
| 187 |
+
requires_grad=True
|
| 188 |
+
)
|
| 189 |
+
self.register_buffer('wavelengths', torch.tensor(wl_np, dtype=torch.float32))
|
| 190 |
+
|
| 191 |
+
print(f"[EVPL_GaussianUnconstrained/MODID] init_λ={[f'{l:.1f}' for l in init_lambdas]}, "
|
| 192 |
+
f"init_std={init_std} (可训练,无约束;原始 std=70.0 固定)")
|
| 193 |
+
|
| 194 |
+
def forward(self, x):
|
| 195 |
+
std = torch.exp(self.log_std)
|
| 196 |
+
kernels = []
|
| 197 |
+
for lam in self.lamda_max:
|
| 198 |
+
w = torch.exp(-((self.wavelengths - lam) ** 2) / (2 * std ** 2))
|
| 199 |
+
w = w / (w.sum() + 1e-6)
|
| 200 |
+
kernels.append(w.unsqueeze(0).unsqueeze(2).unsqueeze(3))
|
| 201 |
+
kernel = torch.cat(kernels, dim=0)
|
| 202 |
+
out = F.conv2d(x, kernel)
|
| 203 |
+
B, C, H, W = out.shape
|
| 204 |
+
flat = out.view(B, C, -1)
|
| 205 |
+
out_min = flat.min(dim=2, keepdim=True)[0].unsqueeze(-1)
|
| 206 |
+
out_max = flat.max(dim=2, keepdim=True)[0].unsqueeze(-1)
|
| 207 |
+
return (out - out_min) / (out_max - out_min + 1e-6)
|
| 208 |
+
|
| 209 |
+
def get_lambda_max(self):
|
| 210 |
+
std = float(torch.exp(self.log_std).detach().item())
|
| 211 |
+
result = {'std': std}
|
| 212 |
+
for i, lam in enumerate(self.lamda_max):
|
| 213 |
+
result[f'lambda_{i+1}'] = float(lam.detach().item())
|
| 214 |
+
return result
|
| 215 |
+
|
| 216 |
+
def print_lambda(self):
|
| 217 |
+
info = self.get_lambda_max()
|
| 218 |
+
vals = [f"λ_{i+1}={info[f'lambda_{i+1}']:.2f}" for i in range(self.out_channels)]
|
| 219 |
+
print(f"[EVPL_GaussianUnconstrained/MODID] {', '.join(vals)}, std={info['std']:.2f} nm")
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
# ====================================================================
|
| 223 |
+
# EVPL_FreeConv
|
| 224 |
+
# ====================================================================
|
| 225 |
+
|
| 226 |
+
class EVPL_FreeConv(nn.Module):
|
| 227 |
+
"""
|
| 228 |
+
Filter Optimization Baseline — 无约束自由 1×1 光谱卷积
|
| 229 |
+
接口与 EVPL 完全一致。
|
| 230 |
+
MODID 仅 16 波段,参数量 3×16=48,过拟合风险低。
|
| 231 |
+
"""
|
| 232 |
+
|
| 233 |
+
def __init__(self, device,
|
| 234 |
+
num_bands: int = NUM_BANDS,
|
| 235 |
+
wl_np: np.ndarray = _WAVELENGTHS_NP):
|
| 236 |
+
super().__init__()
|
| 237 |
+
self.num_bands = num_bands
|
| 238 |
+
self.filter_spectral_response = _FreeSpectralConv(
|
| 239 |
+
device, num_bands=num_bands, wl_np=wl_np, out_channels=3
|
| 240 |
+
)
|
| 241 |
+
print(f"[EVPL_FreeConv/MODID] num_bands={num_bands} (3×{num_bands}={3*num_bands} 参数)")
|
| 242 |
+
|
| 243 |
+
def forward(self, x):
|
| 244 |
+
out = self.filter_spectral_response(x)
|
| 245 |
+
B, C, H, W = out.shape
|
| 246 |
+
flat = out.view(B, C, -1)
|
| 247 |
+
out_min = flat.min(dim=2, keepdim=True)[0].unsqueeze(-1)
|
| 248 |
+
out_max = flat.max(dim=2, keepdim=True)[0].unsqueeze(-1)
|
| 249 |
+
return (out - out_min) / (out_max - out_min + 1e-6)
|
| 250 |
+
|
| 251 |
+
def get_lambda_max(self):
|
| 252 |
+
fsc = self.filter_spectral_response
|
| 253 |
+
peaks = fsc.get_lambda_peak()
|
| 254 |
+
cents = fsc.get_lambda_centroid()
|
| 255 |
+
ents = fsc.get_spectral_entropy()
|
| 256 |
+
fits = fsc.get_lambda_gaussian_fit()
|
| 257 |
+
n = fsc.out_channels
|
| 258 |
+
result = {}
|
| 259 |
+
for i in range(n):
|
| 260 |
+
result[f'lambda_{i+1}'] = cents[i]
|
| 261 |
+
result[f'lambda_{i+1}_peak'] = peaks[i]
|
| 262 |
+
result[f'entropy_{i+1}'] = ents[i]
|
| 263 |
+
if fits:
|
| 264 |
+
for i, fit in enumerate(fits):
|
| 265 |
+
result[f'gauss_mu_{i+1}'] = fit['mu']
|
| 266 |
+
result[f'gauss_sigma_{i+1}'] = fit['sigma']
|
| 267 |
+
result[f'gauss_r2_{i+1}'] = fit['r2']
|
| 268 |
+
return result
|
| 269 |
+
|
| 270 |
+
def print_lambda(self):
|
| 271 |
+
print("[EVPL_FreeConv/MODID]")
|
| 272 |
+
self.filter_spectral_response.print_lambda()
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
# ====================================================================
|
| 276 |
+
# EVPL_PCA
|
| 277 |
+
# ====================================================================
|
| 278 |
+
|
| 279 |
+
class EVPL_PCA(nn.Module):
|
| 280 |
+
"""
|
| 281 |
+
Band Selection Baseline — PCA(投影已在 ModidDataset_PCA 层完成)
|
| 282 |
+
MODID 仅 16 波段,前 3 主成分通常能覆盖 >95% 方差。
|
| 283 |
+
|
| 284 |
+
本模块仅接收已投影的 out_channels 通道输入,
|
| 285 |
+
做通道归一化后输出。参数量 = 0。
|
| 286 |
+
|
| 287 |
+
配套使用:
|
| 288 |
+
from dataloader.modid import ModidDataset_PCA
|
| 289 |
+
train_dataset = ModidDataset_PCA(root_dir, input_shape, train=True)
|
| 290 |
+
# Dataset.__getitem__ 直接返回 [3, H, W] 已投影数据
|
| 291 |
+
evpl_pca = EVPL_PCA(device).to(device)
|
| 292 |
+
"""
|
| 293 |
+
|
| 294 |
+
def __init__(self, device, out_channels: int = 3, **kwargs):
|
| 295 |
+
super().__init__()
|
| 296 |
+
self.out_channels = out_channels
|
| 297 |
+
print(f"[EVPL_PCA/MODID] 就绪,期望 {out_channels} 通道输入"
|
| 298 |
+
f"(PCA 投影已在 ModidDataset_PCA 层完成)")
|
| 299 |
+
|
| 300 |
+
def forward(self, x):
|
| 301 |
+
# x: [B, out_channels, H, W] — 已由 Dataset_PCA 层完成 PCA 投影
|
| 302 |
+
B, C, H, W = x.shape
|
| 303 |
+
flat = x.view(B, C, -1)
|
| 304 |
+
out_min = flat.min(dim=2, keepdim=True)[0].unsqueeze(-1)
|
| 305 |
+
out_max = flat.max(dim=2, keepdim=True)[0].unsqueeze(-1)
|
| 306 |
+
return (x - out_min) / (out_max - out_min + 1e-6)
|
| 307 |
+
|
| 308 |
+
def get_lambda_max(self):
|
| 309 |
+
return {f'lambda_{i+1}': float('nan') for i in range(self.out_channels)}
|
| 310 |
+
|
| 311 |
+
def print_lambda(self):
|
| 312 |
+
print("[EVPL_PCA/MODID] PCA 投影已在 ModidDataset_PCA 层完成,无模型内等效波长信息")
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
# ====================================================================
|
| 316 |
+
# EVPL_SoftBandSelection
|
| 317 |
+
# ====================================================================
|
| 318 |
+
|
| 319 |
+
class EVPL_SoftBandSelection(nn.Module):
|
| 320 |
+
"""
|
| 321 |
+
Band Selection Baseline — Gumbel-Softmax 可微分波段选择
|
| 322 |
+
推理时 hard argmax → λ_max = wavelengths[argmax(logits)]。
|
| 323 |
+
MODID 仅 16 个候选波段,每 epoch 结束调用 anneal_temperature()。
|
| 324 |
+
"""
|
| 325 |
+
|
| 326 |
+
def __init__(self, device,
|
| 327 |
+
num_bands: int = NUM_BANDS,
|
| 328 |
+
wl_np: np.ndarray = _WAVELENGTHS_NP,
|
| 329 |
+
out_channels: int = 3,
|
| 330 |
+
init_temperature: float = 1.0,
|
| 331 |
+
min_temperature: float = 0.1,
|
| 332 |
+
anneal_rate: float = 0.003):
|
| 333 |
+
super().__init__()
|
| 334 |
+
self.num_bands = num_bands
|
| 335 |
+
self.out_channels = out_channels
|
| 336 |
+
self.temperature = init_temperature
|
| 337 |
+
self.min_temperature = min_temperature
|
| 338 |
+
self.anneal_rate = anneal_rate
|
| 339 |
+
self.logits = nn.Parameter(
|
| 340 |
+
torch.randn(out_channels, num_bands, device=device, dtype=torch.float32)
|
| 341 |
+
)
|
| 342 |
+
self.register_buffer('wavelengths', torch.tensor(wl_np, dtype=torch.float32))
|
| 343 |
+
print(f"[EVPL_SoftBandSelection/MODID] num_bands={num_bands}, T={init_temperature}")
|
| 344 |
+
|
| 345 |
+
def anneal_temperature(self):
|
| 346 |
+
self.temperature = max(self.min_temperature,
|
| 347 |
+
self.temperature * math.exp(-self.anneal_rate))
|
| 348 |
+
|
| 349 |
+
def _get_weights(self):
|
| 350 |
+
if self.training:
|
| 351 |
+
return F.gumbel_softmax(self.logits, tau=self.temperature, hard=False, dim=-1)
|
| 352 |
+
else:
|
| 353 |
+
idx = self.logits.argmax(dim=-1, keepdim=True)
|
| 354 |
+
return torch.zeros_like(self.logits).scatter_(-1, idx, 1.0)
|
| 355 |
+
|
| 356 |
+
def forward(self, x):
|
| 357 |
+
weights = self._get_weights()
|
| 358 |
+
kernel = weights.unsqueeze(-1).unsqueeze(-1)
|
| 359 |
+
out = F.conv2d(x, kernel)
|
| 360 |
+
B, C, H, W = out.shape
|
| 361 |
+
flat = out.view(B, C, -1)
|
| 362 |
+
out_min = flat.min(dim=2, keepdim=True)[0].unsqueeze(-1)
|
| 363 |
+
out_max = flat.max(dim=2, keepdim=True)[0].unsqueeze(-1)
|
| 364 |
+
return (out - out_min) / (out_max - out_min + 1e-6)
|
| 365 |
+
|
| 366 |
+
def get_lambda_max(self):
|
| 367 |
+
wl = self.wavelengths
|
| 368 |
+
hard_idx = self.logits.detach().argmax(dim=-1)
|
| 369 |
+
soft_w = F.softmax(self.logits.detach(), dim=-1)
|
| 370 |
+
result = {'temperature': self.temperature}
|
| 371 |
+
for i in range(self.out_channels):
|
| 372 |
+
result[f'lambda_{i+1}'] = float(wl[hard_idx[i]].item())
|
| 373 |
+
result[f'lambda_{i+1}_soft_centroid'] = float(
|
| 374 |
+
((soft_w[i] * wl).sum() / (soft_w[i].sum() + 1e-8)).item()
|
| 375 |
+
)
|
| 376 |
+
return result
|
| 377 |
+
|
| 378 |
+
def print_lambda(self):
|
| 379 |
+
info = self.get_lambda_max()
|
| 380 |
+
print(f"[EVPL_SoftBandSelection/MODID] T={info['temperature']:.4f}")
|
| 381 |
+
for i in range(self.out_channels):
|
| 382 |
+
print(f" ch{i+1}: hard λ={info[f'lambda_{i+1}']:.2f} nm "
|
| 383 |
+
f"soft_centroid={info[f'lambda_{i+1}_soft_centroid']:.2f} nm")
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
# ====================================================================
|
| 387 |
+
# compare_all_baselines
|
| 388 |
+
# ====================================================================
|
| 389 |
+
|
| 390 |
+
def compare_all_baselines(models: dict,
|
| 391 |
+
wl_np: np.ndarray = _WAVELENGTHS_NP,
|
| 392 |
+
num_bands: int = NUM_BANDS,
|
| 393 |
+
save_path: str = None) -> dict:
|
| 394 |
+
"""横向对比 MODID 所有 baseline 的等效 λ_max 与光谱响应。"""
|
| 395 |
+
sep = "=" * 80
|
| 396 |
+
DISPLAY = {
|
| 397 |
+
'evpl': 'EVPL (Fixed Gaussian) [本文]',
|
| 398 |
+
'gauss_nocon': 'Gaussian Unconstrained [消融①]',
|
| 399 |
+
'free': 'Free Spectral Conv [消融②]',
|
| 400 |
+
'pca': 'PCA Projection (fixed) [Band Sel.]',
|
| 401 |
+
'softband': 'Gumbel SoftBand Selection [Band Sel.]',
|
| 402 |
+
}
|
| 403 |
+
print(sep)
|
| 404 |
+
print("MODID 全基线光谱响应对比")
|
| 405 |
+
print(sep)
|
| 406 |
+
all_info = {}
|
| 407 |
+
for name, model in models.items():
|
| 408 |
+
print(f"\n[{DISPLAY.get(name, name)}]")
|
| 409 |
+
model.print_lambda()
|
| 410 |
+
all_info[name] = model.get_lambda_max()
|
| 411 |
+
|
| 412 |
+
_sample_info = next(iter(all_info.values())) if all_info else {}
|
| 413 |
+
n_ch = max(sum(1 for k in _sample_info if k.startswith('lambda_') and k[7:].isdigit()), 1)
|
| 414 |
+
hdr = ' '.join(f"{'Ch'+str(i+1)+' (nm)':>12}" for i in range(n_ch))
|
| 415 |
+
print(f"\n{'':30s} {hdr}")
|
| 416 |
+
print("-" * (32 + 13 * n_ch))
|
| 417 |
+
for name, info in all_info.items():
|
| 418 |
+
disp = DISPLAY.get(name, name)[:28]
|
| 419 |
+
lams = [info.get(f'lambda_{i+1}', float('nan')) for i in range(n_ch)]
|
| 420 |
+
row = ' '.join(f"{l:12.2f}" for l in lams)
|
| 421 |
+
print(f" {disp:28s} {row}")
|
| 422 |
+
|
| 423 |
+
if save_path is not None:
|
| 424 |
+
try:
|
| 425 |
+
import matplotlib
|
| 426 |
+
matplotlib.use('Agg')
|
| 427 |
+
import matplotlib.pyplot as plt
|
| 428 |
+
n_models = len(models)
|
| 429 |
+
_all_colors = ['royalblue', 'seagreen', 'tomato', 'darkorchid',
|
| 430 |
+
'darkorange', 'teal', 'crimson', 'olive']
|
| 431 |
+
ch_colors = _all_colors[:n_ch]
|
| 432 |
+
ch_titles = [f'Ch{i+1}' for i in range(n_ch)]
|
| 433 |
+
fig, axes = plt.subplots(n_models, n_ch, figsize=(5 * n_ch, 3.5 * n_models), sharex=True)
|
| 434 |
+
if n_models == 1:
|
| 435 |
+
axes = axes[np.newaxis, :]
|
| 436 |
+
if n_ch == 1:
|
| 437 |
+
axes = axes[:, np.newaxis]
|
| 438 |
+
for row, (name, model) in enumerate(models.items()):
|
| 439 |
+
resps = _extract_spectral_response(model, wl_np, num_bands)
|
| 440 |
+
for ch in range(n_ch):
|
| 441 |
+
ax = axes[row, ch]
|
| 442 |
+
if resps[ch] is not None:
|
| 443 |
+
r = resps[ch]
|
| 444 |
+
ax.plot(wl_np, r / (r.max() + 1e-8),
|
| 445 |
+
color=ch_colors[ch], linewidth=2, marker='o', markersize=4)
|
| 446 |
+
lam = all_info[name].get(f'lambda_{ch+1}', None)
|
| 447 |
+
if lam and not np.isnan(lam):
|
| 448 |
+
ax.axvline(lam, color='black', linestyle='--', alpha=0.7,
|
| 449 |
+
label=f'λ={lam:.1f}nm')
|
| 450 |
+
if row == 0:
|
| 451 |
+
ax.set_title(ch_titles[ch], fontsize=10)
|
| 452 |
+
if ch == 0:
|
| 453 |
+
ax.set_ylabel(DISPLAY.get(name, name)[:20], fontsize=8)
|
| 454 |
+
if row == n_models - 1:
|
| 455 |
+
ax.set_xlabel('Wavelength (nm)')
|
| 456 |
+
ax.legend(fontsize=7)
|
| 457 |
+
ax.grid(True, alpha=0.3)
|
| 458 |
+
fig.suptitle('MODID Spectral Response — All Baselines', fontsize=13)
|
| 459 |
+
plt.tight_layout()
|
| 460 |
+
plt.savefig(save_path, dpi=150, bbox_inches='tight')
|
| 461 |
+
plt.close(fig)
|
| 462 |
+
print(f"\n [图像已保存] {save_path}")
|
| 463 |
+
except ImportError:
|
| 464 |
+
print(" (matplotlib 不可用,跳过可视化)")
|
| 465 |
+
print(sep)
|
| 466 |
+
return all_info
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
def _extract_spectral_response(model, wl_np, num_bands):
|
| 470 |
+
try:
|
| 471 |
+
if isinstance(model, EVPL):
|
| 472 |
+
fsr = model.filter_spectral_response
|
| 473 |
+
std = fsr.std
|
| 474 |
+
wl_t = fsr.wavelengths
|
| 475 |
+
resps = []
|
| 476 |
+
for lam in [fsr.lamda_max_1, fsr.lamda_max_2, fsr.lamda_max_3]:
|
| 477 |
+
g = torch.exp(-((wl_t - lam) ** 2) / (2 * std ** 2))
|
| 478 |
+
g = g / (g.sum() + 1e-6)
|
| 479 |
+
resps.append(g.detach().cpu().numpy())
|
| 480 |
+
return resps
|
| 481 |
+
elif isinstance(model, EVPL_GaussianUnconstrained):
|
| 482 |
+
std = torch.exp(model.log_std)
|
| 483 |
+
wl_t = model.wavelengths
|
| 484 |
+
resps = []
|
| 485 |
+
for lam in model.lamda_max:
|
| 486 |
+
g = torch.exp(-((wl_t - lam) ** 2) / (2 * std ** 2))
|
| 487 |
+
g = g / (g.sum() + 1e-6)
|
| 488 |
+
resps.append(g.detach().cpu().numpy())
|
| 489 |
+
return resps
|
| 490 |
+
elif isinstance(model, EVPL_FreeConv):
|
| 491 |
+
r = model.filter_spectral_response._get_response()
|
| 492 |
+
n = model.filter_spectral_response.out_channels
|
| 493 |
+
return [r[j].detach().cpu().numpy() for j in range(n)]
|
| 494 |
+
elif isinstance(model, EVPL_PCA):
|
| 495 |
+
return [None, None, None] # 投影在数据集层,无模型内光谱响应
|
| 496 |
+
elif isinstance(model, EVPL_SoftBandSelection):
|
| 497 |
+
soft_w = F.softmax(model.logits.detach(), dim=-1)
|
| 498 |
+
return [soft_w[j].cpu().numpy() for j in range(model.out_channels)]
|
| 499 |
+
except Exception:
|
| 500 |
+
pass
|
| 501 |
+
return [None, None, None]
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
# ====================================================================
|
| 505 |
+
# 快速测试入口
|
| 506 |
+
# ====================================================================
|
| 507 |
+
|
| 508 |
+
if __name__ == "__main__":
|
| 509 |
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 510 |
+
print(f"device: {device}\n")
|
| 511 |
+
print(f"MODID 波段数: {NUM_BANDS}, 波长范围: {SPECTRAL_RANGE[0]:.1f}~{SPECTRAL_RANGE[1]:.1f} nm\n")
|
| 512 |
+
|
| 513 |
+
evpl = EVPL(490.0, 540.0, 570.0, device)
|
| 514 |
+
|
| 515 |
+
gauss_nocon = EVPL_GaussianUnconstrained(device)
|
| 516 |
+
free_conv = EVPL_FreeConv(device)
|
| 517 |
+
# PCA 投影在 ModidDataset_PCA 层完成,模型不需要投影矩阵
|
| 518 |
+
pca_model = EVPL_PCA(device)
|
| 519 |
+
softband = EVPL_SoftBandSelection(device)
|
| 520 |
+
|
| 521 |
+
models = {
|
| 522 |
+
'evpl': evpl, 'gauss_nocon': gauss_nocon,
|
| 523 |
+
'free': free_conv, 'pca': pca_model, 'softband': softband,
|
| 524 |
+
}
|
| 525 |
+
|
| 526 |
+
print("[前向形状验证]")
|
| 527 |
+
x = torch.randn(2, NUM_BANDS, 64, 64).to(device)
|
| 528 |
+
x_pca = torch.randn(2, 3, 64, 64).to(device) # PCA 已在 ModidDataset_PCA 层完成
|
| 529 |
+
for name, m in models.items():
|
| 530 |
+
x_in = x_pca if name == 'pca' else x
|
| 531 |
+
out = m(x_in)
|
| 532 |
+
print(f" {name:14s}: {tuple(x_in.shape)} → {tuple(out.shape)}")
|
| 533 |
+
|
| 534 |
+
print("\n[参数量]")
|
| 535 |
+
for name, m in models.items():
|
| 536 |
+
n = sum(p.numel() for p in m.parameters() if p.requires_grad)
|
| 537 |
+
print(f" {name:14s}: {n:6,}")
|
| 538 |
+
|
| 539 |
+
compare_all_baselines(models, save_path="ablation_modid_baselines_init.png")
|
models/HSI_to_RGB/multi_opsin_evpl.py
ADDED
|
@@ -0,0 +1,304 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Multi-Opsin EVPL 改进版本
|
| 3 |
+
用于 lib_hsi 数据集
|
| 4 |
+
|
| 5 |
+
从 3 个视蛋白 (RGB) 扩展到 5 个 (UVRGNIR),保留更多光谱信息
|
| 6 |
+
并提供可选的特征投影层,增加特征维度以应对 44 类分类
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import math
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn as nn
|
| 12 |
+
import torch.nn.functional as F
|
| 13 |
+
import numpy as np
|
| 14 |
+
|
| 15 |
+
# LIB-HSI 数据集波长数组 (204通道, 400-1000nm VNIR范围)
|
| 16 |
+
wavelengths = np.linspace(400, 1000, 204)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class MultiOpsinEVPL(nn.Module):
|
| 20 |
+
"""
|
| 21 |
+
Multi-Opsin Evolutionary Vision Perception Layer for LIB-HSI dataset
|
| 22 |
+
|
| 23 |
+
改进点:
|
| 24 |
+
1. 从 3 个视蛋白扩展到 5 个 (UV/Blue/Green/Red/NIR)
|
| 25 |
+
- 保留更多光谱信息的细节
|
| 26 |
+
- 避免过度压缩 204 维 → 3 维
|
| 27 |
+
|
| 28 |
+
2. 可选的特征投影层
|
| 29 |
+
- 5 → 64 维特征映射
|
| 30 |
+
- 更好的与 44 类分类对齐
|
| 31 |
+
|
| 32 |
+
3. 数值稳定性改进
|
| 33 |
+
- 高斯核归一化确保输出范围稳定
|
| 34 |
+
- Per-channel 归一化而不是全局
|
| 35 |
+
|
| 36 |
+
4. 参数约束
|
| 37 |
+
- 确保波长在有效范围内
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
def __init__(self, device, use_isp=False, projection_dim=64, use_projection=True):
|
| 41 |
+
"""
|
| 42 |
+
Args:
|
| 43 |
+
device: torch device
|
| 44 |
+
use_isp: 是否使用可逆ISP网络 (默认False)
|
| 45 |
+
projection_dim: 投影维度 (默认64)
|
| 46 |
+
use_projection: 是否使用特征投影层
|
| 47 |
+
"""
|
| 48 |
+
super(MultiOpsinEVPL, self).__init__()
|
| 49 |
+
|
| 50 |
+
self.device = device
|
| 51 |
+
self.use_isp = use_isp
|
| 52 |
+
self.use_projection = use_projection
|
| 53 |
+
self.projection_dim = projection_dim
|
| 54 |
+
|
| 55 |
+
# 5 个视蛋白的可学习波长参数
|
| 56 |
+
self.opsin_wavelengths = nn.ParameterDict({
|
| 57 |
+
'uv': nn.Parameter(torch.tensor(380.0, device=device, dtype=torch.float32)),
|
| 58 |
+
'blue': nn.Parameter(torch.tensor(470.0, device=device, dtype=torch.float32)),
|
| 59 |
+
'green': nn.Parameter(torch.tensor(530.0, device=device, dtype=torch.float32)),
|
| 60 |
+
'red': nn.Parameter(torch.tensor(600.0, device=device, dtype=torch.float32)),
|
| 61 |
+
'nir': nn.Parameter(torch.tensor(850.0, device=device, dtype=torch.float32)),
|
| 62 |
+
})
|
| 63 |
+
|
| 64 |
+
# 波长数组 (204 通道)
|
| 65 |
+
self.register_buffer('wavelengths', torch.tensor(
|
| 66 |
+
wavelengths, dtype=torch.float32, device=device
|
| 67 |
+
))
|
| 68 |
+
|
| 69 |
+
# 固定的高斯核标准差
|
| 70 |
+
# 对于 5 个视蛋白,使用较窄的 σ (40nm) 避免过度重叠
|
| 71 |
+
self.std = 40.0
|
| 72 |
+
|
| 73 |
+
# 可选的特征投影层
|
| 74 |
+
if use_projection:
|
| 75 |
+
# 5 维 → 64 维, 使用并行路径
|
| 76 |
+
self.projection = nn.Sequential(
|
| 77 |
+
nn.Conv2d(5, 32, kernel_size=3, padding=1),
|
| 78 |
+
nn.BatchNorm2d(32),
|
| 79 |
+
nn.ReLU(inplace=True),
|
| 80 |
+
nn.Conv2d(32, projection_dim, kernel_size=1),
|
| 81 |
+
)
|
| 82 |
+
self.out_channels = projection_dim
|
| 83 |
+
else:
|
| 84 |
+
self.out_channels = 5
|
| 85 |
+
|
| 86 |
+
def forward(self, x):
|
| 87 |
+
"""
|
| 88 |
+
Args:
|
| 89 |
+
x: 高光谱图像 [B, 204, H, W]
|
| 90 |
+
|
| 91 |
+
Returns:
|
| 92 |
+
output: [B, out_channels, H, W]
|
| 93 |
+
如果 use_projection=True, out_channels=64
|
| 94 |
+
否则 out_channels=5
|
| 95 |
+
"""
|
| 96 |
+
# Step 1: 生成 5 个视蛋白的响应
|
| 97 |
+
opsin_responses = self._create_multi_opsin_response(x) # [B, 5, H, W]
|
| 98 |
+
|
| 99 |
+
# Step 2: 可选的特征投影
|
| 100 |
+
if self.use_projection:
|
| 101 |
+
output = self.projection(opsin_responses) # [B, projection_dim, H, W]
|
| 102 |
+
else:
|
| 103 |
+
output = opsin_responses
|
| 104 |
+
|
| 105 |
+
return output
|
| 106 |
+
|
| 107 |
+
def _create_multi_opsin_response(self, x):
|
| 108 |
+
"""
|
| 109 |
+
生成 5 个视蛋白的光谱响应
|
| 110 |
+
|
| 111 |
+
Args:
|
| 112 |
+
x: [B, 204, H, W]
|
| 113 |
+
|
| 114 |
+
Returns:
|
| 115 |
+
responses: [B, 5, H, W]
|
| 116 |
+
"""
|
| 117 |
+
B, C, H, W = x.shape
|
| 118 |
+
|
| 119 |
+
# 高斯核权重计算
|
| 120 |
+
weights = {}
|
| 121 |
+
for name, lamda_max in self.opsin_wavelengths.items():
|
| 122 |
+
# 高斯核: exp(-(λ - λ_max)^2 / (2σ^2))
|
| 123 |
+
w = torch.exp(
|
| 124 |
+
-(self.wavelengths - lamda_max) ** 2 / (2 * self.std ** 2)
|
| 125 |
+
)
|
| 126 |
+
# 归一化: 确保和为 1
|
| 127 |
+
w = w / (w.sum() + 1e-8)
|
| 128 |
+
weights[name] = w # [204]
|
| 129 |
+
|
| 130 |
+
# 对每个视蛋白进行加权求和
|
| 131 |
+
responses = []
|
| 132 |
+
for name in ['uv', 'blue', 'green', 'red', 'nir']:
|
| 133 |
+
w = weights[name].view(1, C, 1, 1) # [1, 204, 1, 1]
|
| 134 |
+
|
| 135 |
+
# 加权求和
|
| 136 |
+
response = (x * w).sum(dim=1, keepdim=True) # [B, 1, H, W]
|
| 137 |
+
|
| 138 |
+
# 数值稳定性: 限制范围
|
| 139 |
+
response = torch.clamp(response, 0, 1)
|
| 140 |
+
responses.append(response)
|
| 141 |
+
|
| 142 |
+
# 拼接: [B, 5, H, W]
|
| 143 |
+
output = torch.cat(responses, dim=1)
|
| 144 |
+
|
| 145 |
+
return output
|
| 146 |
+
|
| 147 |
+
def get_wavelengths(self):
|
| 148 |
+
"""获取当前学习到的视蛋白波长"""
|
| 149 |
+
return {
|
| 150 |
+
'uv': self.opsin_wavelengths['uv'].item(),
|
| 151 |
+
'blue': self.opsin_wavelengths['blue'].item(),
|
| 152 |
+
'green': self.opsin_wavelengths['green'].item(),
|
| 153 |
+
'red': self.opsin_wavelengths['red'].item(),
|
| 154 |
+
'nir': self.opsin_wavelengths['nir'].item(),
|
| 155 |
+
'std': self.std,
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
def constrain_wavelengths(self):
|
| 159 |
+
"""约束波长参数在有效范围内"""
|
| 160 |
+
with torch.no_grad():
|
| 161 |
+
# UV: 350-400 nm
|
| 162 |
+
self.opsin_wavelengths['uv'].clamp_(350, 400)
|
| 163 |
+
# Blue: 450-480 nm
|
| 164 |
+
self.opsin_wavelengths['blue'].clamp_(450, 480)
|
| 165 |
+
# Green: 500-550 nm
|
| 166 |
+
self.opsin_wavelengths['green'].clamp_(500, 550)
|
| 167 |
+
# Red: 580-620 nm
|
| 168 |
+
self.opsin_wavelengths['red'].clamp_(580, 620)
|
| 169 |
+
# NIR: 800-950 nm
|
| 170 |
+
self.opsin_wavelengths['nir'].clamp_(800, 950)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
class OriginalEVPL(nn.Module):
|
| 174 |
+
"""
|
| 175 |
+
原始的 3 个视蛋白 EVPL (用于对比实验)
|
| 176 |
+
"""
|
| 177 |
+
|
| 178 |
+
def __init__(self, lamda_max_1, lamda_max_2, lamda_max_3, device):
|
| 179 |
+
super(OriginalEVPL, self).__init__()
|
| 180 |
+
self.filter_spectral_response = Gaussian_kernel_conv2d(
|
| 181 |
+
lamda_max_1, lamda_max_2, lamda_max_3, device
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
def forward(self, x):
|
| 185 |
+
x = self.filter_spectral_response(x)
|
| 186 |
+
# 输出归一化到 [0, 1] 范围
|
| 187 |
+
B, C, H, W = x.shape
|
| 188 |
+
x_flat = x.view(B, C, -1)
|
| 189 |
+
x_min = x_flat.min(dim=2, keepdim=True)[0].unsqueeze(-1)
|
| 190 |
+
x_max = x_flat.max(dim=2, keepdim=True)[0].unsqueeze(-1)
|
| 191 |
+
x = (x - x_min) / (x_max - x_min + 1e-6)
|
| 192 |
+
return x
|
| 193 |
+
|
| 194 |
+
def get_lambda_max(self):
|
| 195 |
+
return {
|
| 196 |
+
'lambda_1': self.filter_spectral_response.lamda_max_1.item(),
|
| 197 |
+
'lambda_2': self.filter_spectral_response.lamda_max_2.item(),
|
| 198 |
+
'lambda_3': self.filter_spectral_response.lamda_max_3.item(),
|
| 199 |
+
'std': self.filter_spectral_response.std,
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
class Gaussian_kernel_conv2d(nn.Module):
|
| 204 |
+
"""
|
| 205 |
+
高斯核卷积层 (原始版本)
|
| 206 |
+
"""
|
| 207 |
+
|
| 208 |
+
def __init__(self, lamda_max_1, lamda_max_2, lamda_max_3, device, trainable=True):
|
| 209 |
+
super(Gaussian_kernel_conv2d, self).__init__()
|
| 210 |
+
|
| 211 |
+
self.lamda_max_1 = nn.Parameter(
|
| 212 |
+
torch.tensor(lamda_max_1, device=device, dtype=torch.float32),
|
| 213 |
+
requires_grad=trainable
|
| 214 |
+
)
|
| 215 |
+
self.lamda_max_2 = nn.Parameter(
|
| 216 |
+
torch.tensor(lamda_max_2, device=device, dtype=torch.float32),
|
| 217 |
+
requires_grad=trainable
|
| 218 |
+
)
|
| 219 |
+
self.lamda_max_3 = nn.Parameter(
|
| 220 |
+
torch.tensor(lamda_max_3, device=device, dtype=torch.float32),
|
| 221 |
+
requires_grad=trainable
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
self.register_buffer('wavelengths', torch.tensor(
|
| 225 |
+
wavelengths, dtype=torch.float32
|
| 226 |
+
))
|
| 227 |
+
|
| 228 |
+
self.std = 60.0
|
| 229 |
+
self.device = device
|
| 230 |
+
|
| 231 |
+
def forward(self, x):
|
| 232 |
+
# [B, 204, H, W]
|
| 233 |
+
B, C, H, W = x.shape
|
| 234 |
+
|
| 235 |
+
# 高斯核权重
|
| 236 |
+
w1 = torch.exp(-(self.wavelengths - self.lamda_max_1) ** 2 / (2 * self.std ** 2))
|
| 237 |
+
w2 = torch.exp(-(self.wavelengths - self.lamda_max_2) ** 2 / (2 * self.std ** 2))
|
| 238 |
+
w3 = torch.exp(-(self.wavelengths - self.lamda_max_3) ** 2 / (2 * self.std ** 2))
|
| 239 |
+
|
| 240 |
+
# 归一化
|
| 241 |
+
w1 = w1 / (w1.sum() + 1e-8)
|
| 242 |
+
w2 = w2 / (w2.sum() + 1e-8)
|
| 243 |
+
w3 = w3 / (w3.sum() + 1e-8)
|
| 244 |
+
|
| 245 |
+
# 加权求和得到 RGB 三通道
|
| 246 |
+
w1 = w1.view(1, C, 1, 1)
|
| 247 |
+
w2 = w2.view(1, C, 1, 1)
|
| 248 |
+
w3 = w3.view(1, C, 1, 1)
|
| 249 |
+
|
| 250 |
+
r = (x * w1).sum(dim=1, keepdim=True)
|
| 251 |
+
g = (x * w2).sum(dim=1, keepdim=True)
|
| 252 |
+
b = (x * w3).sum(dim=1, keepdim=True)
|
| 253 |
+
|
| 254 |
+
output = torch.cat([r, g, b], dim=1) # [B, 3, H, W]
|
| 255 |
+
|
| 256 |
+
return output
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
if __name__ == '__main__':
|
| 260 |
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 261 |
+
|
| 262 |
+
# 测试 MultiOpsinEVPL
|
| 263 |
+
print("=" * 60)
|
| 264 |
+
print("Testing MultiOpsinEVPL")
|
| 265 |
+
print("=" * 60)
|
| 266 |
+
|
| 267 |
+
evpl_multi = MultiOpsinEVPL(
|
| 268 |
+
device=device,
|
| 269 |
+
use_projection=True,
|
| 270 |
+
projection_dim=64
|
| 271 |
+
)
|
| 272 |
+
evpl_multi = evpl_multi.to(device)
|
| 273 |
+
|
| 274 |
+
# 模拟高光谱输入
|
| 275 |
+
hsi_input = torch.randn(2, 204, 256, 256).to(device)
|
| 276 |
+
|
| 277 |
+
output = evpl_multi(hsi_input)
|
| 278 |
+
print(f"Input shape: {hsi_input.shape}")
|
| 279 |
+
print(f"Output shape: {output.shape}")
|
| 280 |
+
print(f"Expected output shape: [2, 64, 256, 256]")
|
| 281 |
+
print(f"✓ Multi-Opsin EVPL works correctly!")
|
| 282 |
+
|
| 283 |
+
# 显示学习到的波长
|
| 284 |
+
wavelengths_dict = evpl_multi.get_wavelengths()
|
| 285 |
+
print("\nLearned wavelengths:")
|
| 286 |
+
for name, wl in wavelengths_dict.items():
|
| 287 |
+
if name != 'std':
|
| 288 |
+
print(f" {name}: {wl:.1f} nm")
|
| 289 |
+
|
| 290 |
+
# 计算参数数量
|
| 291 |
+
total_params = sum(p.numel() for p in evpl_multi.parameters())
|
| 292 |
+
print(f"\nTotal parameters: {total_params}")
|
| 293 |
+
|
| 294 |
+
# 对比原始 EVPL
|
| 295 |
+
print("\n" + "=" * 60)
|
| 296 |
+
print("Comparison with Original EVPL")
|
| 297 |
+
print("=" * 60)
|
| 298 |
+
|
| 299 |
+
evpl_original = OriginalEVPL(450.0, 530.0, 580.0, device).to(device)
|
| 300 |
+
output_original = evpl_original(hsi_input)
|
| 301 |
+
|
| 302 |
+
print(f"Original EVPL output shape: {output_original.shape}")
|
| 303 |
+
print(f"Multi-Opsin EVPL output shape: {output.shape}")
|
| 304 |
+
print(f"Information preservation: 5 channels > 3 channels ✓")
|
models/HSI_to_RGB/rgb_opsin.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""RGB opsin layer for MinnApple detection/counting (3-channel input)."""
|
| 2 |
+
|
| 3 |
+
import math
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class RGBOpsinLayer(nn.Module):
|
| 10 |
+
"""Simulate opsin spectral response on RGB channels with Gaussian kernels."""
|
| 11 |
+
|
| 12 |
+
def __init__(self, peaks=(650.0, 550.0, 450.0), trainable=False, std=25.0):
|
| 13 |
+
super().__init__()
|
| 14 |
+
self.std = std
|
| 15 |
+
# Map RGB band indices to pseudo-wavelengths 450-650 nm
|
| 16 |
+
wl = torch.tensor([450.0, 550.0, 650.0])
|
| 17 |
+
self.register_buffer('wavelengths', wl)
|
| 18 |
+
self.lamda_max_1 = nn.Parameter(torch.tensor(float(peaks[0])), requires_grad=trainable)
|
| 19 |
+
self.lamda_max_2 = nn.Parameter(torch.tensor(float(peaks[1])), requires_grad=trainable)
|
| 20 |
+
self.lamda_max_3 = nn.Parameter(torch.tensor(float(peaks[2])), requires_grad=trainable)
|
| 21 |
+
self.trainable = trainable
|
| 22 |
+
|
| 23 |
+
def _kernel(self, lam):
|
| 24 |
+
std = self.std
|
| 25 |
+
x = self.wavelengths
|
| 26 |
+
return (1 / (std * (2 * math.pi) ** 0.5) *
|
| 27 |
+
torch.exp(-((x - lam) ** 2) / (2 * std ** 2)))
|
| 28 |
+
|
| 29 |
+
def forward(self, x):
|
| 30 |
+
# 3 opsins × 3 RGB bands -> [3, 3] spectral mixing matrix
|
| 31 |
+
k1 = self._kernel(self.lamda_max_1)
|
| 32 |
+
k2 = self._kernel(self.lamda_max_2)
|
| 33 |
+
k3 = self._kernel(self.lamda_max_3)
|
| 34 |
+
M = torch.stack([k1, k2, k3], dim=0)
|
| 35 |
+
M = M / (M.sum(dim=1, keepdim=True) + 1e-8)
|
| 36 |
+
weight = M.view(3, 3, 1, 1)
|
| 37 |
+
return F.conv2d(x, weight)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class RGBFreeConvOpsin(nn.Module):
|
| 41 |
+
"""FreeConv-style learnable 3×3 spectral mixing."""
|
| 42 |
+
|
| 43 |
+
def __init__(self):
|
| 44 |
+
super().__init__()
|
| 45 |
+
self.conv = nn.Conv2d(3, 3, kernel_size=1, bias=False)
|
| 46 |
+
|
| 47 |
+
def forward(self, x):
|
| 48 |
+
return self.conv(x)
|
models/__init__.py
ADDED
|
File without changes
|
models/backbone/__init__.py
ADDED
|
File without changes
|
models/backbone/encoder_factory.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Post-SegFormer segmentation encoders via timm (features_only).
|
| 3 |
+
|
| 4 |
+
Selected encoders (published after / competitive with SegFormer 2021):
|
| 5 |
+
- pvt_v2_b2 : PVT v2 (NeurIPS 2022)
|
| 6 |
+
- convnext_tiny: ConvNeXt (CVPR 2022)
|
| 7 |
+
- swinv2_tiny_window8_256: Swin Transformer V2 (2022)
|
| 8 |
+
- poolformer_s12: PoolFormer / MetaFormer (CVPR 2022)
|
| 9 |
+
- twins_svt_small: Twins-SVT (NeurIPS 2021, widely used post-SegFormer baseline)
|
| 10 |
+
|
| 11 |
+
Each wrapper exposes `.embed_dims` (4-stage channel dims) and returns
|
| 12 |
+
[C1, C2, C3, C4] feature maps compatible with SegFormerHead.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import timm
|
| 16 |
+
import torch.nn as nn
|
| 17 |
+
|
| 18 |
+
# mit_b0 embed_dims for reference: [32, 64, 160, 256]
|
| 19 |
+
ENCODER_SPECS = {
|
| 20 |
+
'mit_b0': {'type': 'mit', 'embed_dims': [32, 64, 160, 256]},
|
| 21 |
+
'mit_b1': {'type': 'mit', 'embed_dims': [64, 128, 320, 512]},
|
| 22 |
+
'pvt_v2_b2': {'type': 'timm', 'model': 'pvt_v2_b2', 'embed_dims': [64, 128, 320, 512]},
|
| 23 |
+
'convnext_tiny': {'type': 'timm', 'model': 'convnext_tiny', 'embed_dims': [96, 192, 384, 768]},
|
| 24 |
+
'swinv2_tiny': {'type': 'timm', 'model': 'swinv2_tiny_window8_256', 'embed_dims': [96, 192, 384, 768], 'fixed_size': 256},
|
| 25 |
+
'poolformer_s12': {'type': 'timm', 'model': 'poolformer_s12', 'embed_dims': [64, 128, 320, 512]},
|
| 26 |
+
'twins_svt_small': {'type': 'timm', 'model': 'twins_svt_small', 'embed_dims': [64, 128, 256, 512]},
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
POST_SEGFORMER_ENCODERS = [
|
| 30 |
+
'pvt_v2_b2', 'convnext_tiny', 'swinv2_tiny', 'poolformer_s12', 'twins_svt_small'
|
| 31 |
+
]
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class TimmEncoderBackbone(nn.Module):
|
| 35 |
+
"""Wrap timm features_only model to match MiT output interface."""
|
| 36 |
+
|
| 37 |
+
def __init__(self, model_name, embed_dims, pretrained=False, fixed_size=None):
|
| 38 |
+
super().__init__()
|
| 39 |
+
self.embed_dims = embed_dims
|
| 40 |
+
self.model_name = model_name
|
| 41 |
+
self.fixed_size = fixed_size # e.g. 256 for SwinV2 window models
|
| 42 |
+
self.backbone = timm.create_model(
|
| 43 |
+
model_name,
|
| 44 |
+
features_only=True,
|
| 45 |
+
out_indices=(0, 1, 2, 3),
|
| 46 |
+
pretrained=pretrained,
|
| 47 |
+
in_chans=3,
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
def forward(self, x):
|
| 51 |
+
import torch.nn.functional as F
|
| 52 |
+
b, c, h, w = x.shape
|
| 53 |
+
if self.fixed_size is not None:
|
| 54 |
+
x_in = F.interpolate(x, size=(self.fixed_size, self.fixed_size),
|
| 55 |
+
mode='bilinear', align_corners=False)
|
| 56 |
+
else:
|
| 57 |
+
x_in = x
|
| 58 |
+
feats = self.backbone(x_in)
|
| 59 |
+
outs = []
|
| 60 |
+
strides = [4, 8, 16, 32]
|
| 61 |
+
for i, f in enumerate(feats):
|
| 62 |
+
# Swin / some ViT backbones return NHWC
|
| 63 |
+
if f.dim() == 4 and f.shape[-1] == self.embed_dims[i] and f.shape[1] != self.embed_dims[i]:
|
| 64 |
+
f = f.permute(0, 3, 1, 2).contiguous()
|
| 65 |
+
if self.fixed_size is not None:
|
| 66 |
+
th, tw = max(1, h // strides[i]), max(1, w // strides[i])
|
| 67 |
+
f = F.interpolate(f, size=(th, tw), mode='bilinear', align_corners=False)
|
| 68 |
+
outs.append(f)
|
| 69 |
+
return outs
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def build_encoder(encoder_type, pretrained=False):
|
| 73 |
+
"""Build segmentation encoder; returns nn.Module with .embed_dims."""
|
| 74 |
+
if encoder_type not in ENCODER_SPECS:
|
| 75 |
+
raise ValueError(
|
| 76 |
+
f"Unknown encoder '{encoder_type}'. "
|
| 77 |
+
f"Choose from: {list(ENCODER_SPECS.keys())}"
|
| 78 |
+
)
|
| 79 |
+
spec = ENCODER_SPECS[encoder_type]
|
| 80 |
+
if spec['type'] == 'mit':
|
| 81 |
+
from models.backbone.mix_transformer import mit_b0, mit_b1, mit_b3, mit_b5
|
| 82 |
+
factories = {
|
| 83 |
+
'mit_b0': mit_b0, 'mit_b1': mit_b1,
|
| 84 |
+
'mit_b3': mit_b3, 'mit_b5': mit_b5,
|
| 85 |
+
}
|
| 86 |
+
return factories[encoder_type]()
|
| 87 |
+
return TimmEncoderBackbone(
|
| 88 |
+
spec['model'],
|
| 89 |
+
spec['embed_dims'],
|
| 90 |
+
pretrained=pretrained,
|
| 91 |
+
fixed_size=spec.get('fixed_size'),
|
| 92 |
+
)
|
models/backbone/mix_transformer.py
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
from functools import partial
|
| 5 |
+
from timm.models.layers import DropPath, to_2tuple, trunc_normal_
|
| 6 |
+
import math
|
| 7 |
+
|
| 8 |
+
class Mlp(nn.Module):
|
| 9 |
+
|
| 10 |
+
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.0):
|
| 11 |
+
super().__init__()
|
| 12 |
+
out_features = out_features or in_features
|
| 13 |
+
hidden_features = hidden_features or in_features
|
| 14 |
+
self.fc1 = nn.Linear(in_features, hidden_features)
|
| 15 |
+
self.dwconv = DWConv(hidden_features)
|
| 16 |
+
self.act = act_layer()
|
| 17 |
+
self.fc2 = nn.Linear(hidden_features, out_features)
|
| 18 |
+
self.drop = nn.Dropout(drop)
|
| 19 |
+
self.apply(self._init_weights)
|
| 20 |
+
|
| 21 |
+
def _init_weights(self, m):
|
| 22 |
+
if isinstance(m, nn.Linear):
|
| 23 |
+
trunc_normal_(m.weight, std=0.02)
|
| 24 |
+
if isinstance(m, nn.Linear) and m.bias is not None:
|
| 25 |
+
nn.init.constant_(m.bias, 0)
|
| 26 |
+
elif isinstance(m, nn.LayerNorm):
|
| 27 |
+
nn.init.constant_(m.bias, 0)
|
| 28 |
+
nn.init.constant_(m.weight, 1.0)
|
| 29 |
+
elif isinstance(m, nn.Conv2d):
|
| 30 |
+
fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
|
| 31 |
+
fan_out //= m.groups
|
| 32 |
+
m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
|
| 33 |
+
if m.bias is not None:
|
| 34 |
+
m.bias.data.zero_()
|
| 35 |
+
|
| 36 |
+
def forward(self, x, H, W):
|
| 37 |
+
x = self.fc1(x)
|
| 38 |
+
x = self.dwconv(x, H, W)
|
| 39 |
+
x = self.act(x)
|
| 40 |
+
x = self.drop(x)
|
| 41 |
+
x = self.fc2(x)
|
| 42 |
+
x = self.drop(x)
|
| 43 |
+
return x
|
| 44 |
+
|
| 45 |
+
class Attention(nn.Module):
|
| 46 |
+
|
| 47 |
+
def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.0, proj_drop=0.0, sr_ratio=1):
|
| 48 |
+
super().__init__()
|
| 49 |
+
assert dim % num_heads == 0, f'dim {dim} should be divided by num_heads {num_heads}.'
|
| 50 |
+
self.dim = dim
|
| 51 |
+
self.num_heads = num_heads
|
| 52 |
+
head_dim = dim // num_heads
|
| 53 |
+
self.scale = qk_scale or head_dim ** (-0.5)
|
| 54 |
+
self.q = nn.Linear(dim, dim, bias=qkv_bias)
|
| 55 |
+
self.kv = nn.Linear(dim, dim * 2, bias=qkv_bias)
|
| 56 |
+
self.attn_drop = nn.Dropout(attn_drop)
|
| 57 |
+
self.proj = nn.Linear(dim, dim)
|
| 58 |
+
self.proj_drop = nn.Dropout(proj_drop)
|
| 59 |
+
self.sr_ratio = sr_ratio
|
| 60 |
+
if sr_ratio > 1:
|
| 61 |
+
self.sr = nn.Conv2d(dim, dim, kernel_size=sr_ratio, stride=sr_ratio)
|
| 62 |
+
self.norm = nn.LayerNorm(dim)
|
| 63 |
+
self.apply(self._init_weights)
|
| 64 |
+
|
| 65 |
+
def _init_weights(self, m):
|
| 66 |
+
if isinstance(m, nn.Linear):
|
| 67 |
+
trunc_normal_(m.weight, std=0.02)
|
| 68 |
+
if isinstance(m, nn.Linear) and m.bias is not None:
|
| 69 |
+
nn.init.constant_(m.bias, 0)
|
| 70 |
+
elif isinstance(m, nn.LayerNorm):
|
| 71 |
+
nn.init.constant_(m.bias, 0)
|
| 72 |
+
nn.init.constant_(m.weight, 1.0)
|
| 73 |
+
elif isinstance(m, nn.Conv2d):
|
| 74 |
+
fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
|
| 75 |
+
fan_out //= m.groups
|
| 76 |
+
m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
|
| 77 |
+
if m.bias is not None:
|
| 78 |
+
m.bias.data.zero_()
|
| 79 |
+
|
| 80 |
+
def forward(self, x, H, W):
|
| 81 |
+
(B, N, C) = x.shape
|
| 82 |
+
q = self.q(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
|
| 83 |
+
if self.sr_ratio > 1:
|
| 84 |
+
x_ = x.permute(0, 2, 1).reshape(B, C, H, W)
|
| 85 |
+
x_ = self.sr(x_).reshape(B, C, -1).permute(0, 2, 1)
|
| 86 |
+
x_ = self.norm(x_)
|
| 87 |
+
kv = self.kv(x_).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
|
| 88 |
+
else:
|
| 89 |
+
kv = self.kv(x).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
|
| 90 |
+
(k, v) = (kv[0], kv[1])
|
| 91 |
+
attn = q @ k.transpose(-2, -1) * self.scale
|
| 92 |
+
attn = attn.softmax(dim=-1)
|
| 93 |
+
attn = self.attn_drop(attn)
|
| 94 |
+
x = (attn @ v).transpose(1, 2).reshape(B, N, C)
|
| 95 |
+
x = self.proj(x)
|
| 96 |
+
x = self.proj_drop(x)
|
| 97 |
+
return x
|
| 98 |
+
|
| 99 |
+
class Block(nn.Module):
|
| 100 |
+
|
| 101 |
+
def __init__(self, dim, num_heads, mlp_ratio=4.0, qkv_bias=False, qk_scale=None, drop=0.0, attn_drop=0.0, drop_path=0.0, act_layer=nn.GELU, norm_layer=nn.LayerNorm, sr_ratio=1):
|
| 102 |
+
super().__init__()
|
| 103 |
+
self.norm1 = norm_layer(dim)
|
| 104 |
+
self.attn = Attention(dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop, sr_ratio=sr_ratio)
|
| 105 |
+
self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
|
| 106 |
+
self.norm2 = norm_layer(dim)
|
| 107 |
+
mlp_hidden_dim = int(dim * mlp_ratio)
|
| 108 |
+
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
|
| 109 |
+
self.apply(self._init_weights)
|
| 110 |
+
|
| 111 |
+
def _init_weights(self, m):
|
| 112 |
+
if isinstance(m, nn.Linear):
|
| 113 |
+
trunc_normal_(m.weight, std=0.02)
|
| 114 |
+
if isinstance(m, nn.Linear) and m.bias is not None:
|
| 115 |
+
nn.init.constant_(m.bias, 0)
|
| 116 |
+
elif isinstance(m, nn.LayerNorm):
|
| 117 |
+
nn.init.constant_(m.bias, 0)
|
| 118 |
+
nn.init.constant_(m.weight, 1.0)
|
| 119 |
+
elif isinstance(m, nn.Conv2d):
|
| 120 |
+
fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
|
| 121 |
+
fan_out //= m.groups
|
| 122 |
+
m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
|
| 123 |
+
if m.bias is not None:
|
| 124 |
+
m.bias.data.zero_()
|
| 125 |
+
|
| 126 |
+
def forward(self, x, H, W):
|
| 127 |
+
x = x + self.drop_path(self.attn(self.norm1(x), H, W))
|
| 128 |
+
x = x + self.drop_path(self.mlp(self.norm2(x), H, W))
|
| 129 |
+
return x
|
| 130 |
+
|
| 131 |
+
class OverlapPatchEmbed(nn.Module):
|
| 132 |
+
|
| 133 |
+
def __init__(self, img_size=224, patch_size=7, stride=4, in_chans=3, embed_dim=768):
|
| 134 |
+
super().__init__()
|
| 135 |
+
img_size = to_2tuple(img_size)
|
| 136 |
+
patch_size = to_2tuple(patch_size)
|
| 137 |
+
self.img_size = img_size
|
| 138 |
+
self.patch_size = patch_size
|
| 139 |
+
(self.H, self.W) = (img_size[0] // patch_size[0], img_size[1] // patch_size[1])
|
| 140 |
+
self.num_patches = self.H * self.W
|
| 141 |
+
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=stride, padding=(patch_size[0] // 2, patch_size[1] // 2))
|
| 142 |
+
self.norm = nn.LayerNorm(embed_dim)
|
| 143 |
+
self.apply(self._init_weights)
|
| 144 |
+
|
| 145 |
+
def _init_weights(self, m):
|
| 146 |
+
if isinstance(m, nn.Linear):
|
| 147 |
+
trunc_normal_(m.weight, std=0.02)
|
| 148 |
+
if isinstance(m, nn.Linear) and m.bias is not None:
|
| 149 |
+
nn.init.constant_(m.bias, 0)
|
| 150 |
+
elif isinstance(m, nn.LayerNorm):
|
| 151 |
+
nn.init.constant_(m.bias, 0)
|
| 152 |
+
nn.init.constant_(m.weight, 1.0)
|
| 153 |
+
elif isinstance(m, nn.Conv2d):
|
| 154 |
+
fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
|
| 155 |
+
fan_out //= m.groups
|
| 156 |
+
m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
|
| 157 |
+
if m.bias is not None:
|
| 158 |
+
m.bias.data.zero_()
|
| 159 |
+
|
| 160 |
+
def forward(self, x):
|
| 161 |
+
x = self.proj(x)
|
| 162 |
+
(_, _, H, W) = x.shape
|
| 163 |
+
x = x.flatten(2).transpose(1, 2)
|
| 164 |
+
x = self.norm(x)
|
| 165 |
+
return (x, H, W)
|
| 166 |
+
|
| 167 |
+
class MixVisionTransformer(nn.Module):
|
| 168 |
+
|
| 169 |
+
def __init__(self, img_size=224, patch_size=16, in_chans=3, num_classes=1000, embed_dims=[64, 128, 256, 512], num_heads=[1, 2, 4, 8], mlp_ratios=[4, 4, 4, 4], qkv_bias=False, qk_scale=None, drop_rate=0.0, attn_drop_rate=0.0, drop_path_rate=0.0, norm_layer=nn.LayerNorm, depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1]):
|
| 170 |
+
super().__init__()
|
| 171 |
+
self.num_classes = num_classes
|
| 172 |
+
self.depths = depths
|
| 173 |
+
self.embed_dims = embed_dims
|
| 174 |
+
self.patch_embed1 = OverlapPatchEmbed(img_size=img_size, patch_size=7, stride=4, in_chans=in_chans, embed_dim=embed_dims[0])
|
| 175 |
+
self.patch_embed2 = OverlapPatchEmbed(img_size=img_size // 4, patch_size=3, stride=2, in_chans=embed_dims[0], embed_dim=embed_dims[1])
|
| 176 |
+
self.patch_embed3 = OverlapPatchEmbed(img_size=img_size // 8, patch_size=3, stride=2, in_chans=embed_dims[1], embed_dim=embed_dims[2])
|
| 177 |
+
self.patch_embed4 = OverlapPatchEmbed(img_size=img_size // 16, patch_size=3, stride=2, in_chans=embed_dims[2], embed_dim=embed_dims[3])
|
| 178 |
+
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))]
|
| 179 |
+
cur = 0
|
| 180 |
+
self.block1 = nn.ModuleList([Block(dim=embed_dims[0], num_heads=num_heads[0], mlp_ratio=mlp_ratios[0], qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer, sr_ratio=sr_ratios[0]) for i in range(depths[0])])
|
| 181 |
+
self.norm1 = norm_layer(embed_dims[0])
|
| 182 |
+
cur += depths[0]
|
| 183 |
+
self.block2 = nn.ModuleList([Block(dim=embed_dims[1], num_heads=num_heads[1], mlp_ratio=mlp_ratios[1], qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer, sr_ratio=sr_ratios[1]) for i in range(depths[1])])
|
| 184 |
+
self.norm2 = norm_layer(embed_dims[1])
|
| 185 |
+
cur += depths[1]
|
| 186 |
+
self.block3 = nn.ModuleList([Block(dim=embed_dims[2], num_heads=num_heads[2], mlp_ratio=mlp_ratios[2], qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer, sr_ratio=sr_ratios[2]) for i in range(depths[2])])
|
| 187 |
+
self.norm3 = norm_layer(embed_dims[2])
|
| 188 |
+
cur += depths[2]
|
| 189 |
+
self.block4 = nn.ModuleList([Block(dim=embed_dims[3], num_heads=num_heads[3], mlp_ratio=mlp_ratios[3], qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer, sr_ratio=sr_ratios[3]) for i in range(depths[3])])
|
| 190 |
+
self.norm4 = norm_layer(embed_dims[3])
|
| 191 |
+
self.apply(self._init_weights)
|
| 192 |
+
|
| 193 |
+
def _init_weights(self, m):
|
| 194 |
+
if isinstance(m, nn.Linear):
|
| 195 |
+
trunc_normal_(m.weight, std=0.02)
|
| 196 |
+
if isinstance(m, nn.Linear) and m.bias is not None:
|
| 197 |
+
nn.init.constant_(m.bias, 0)
|
| 198 |
+
elif isinstance(m, nn.LayerNorm):
|
| 199 |
+
nn.init.constant_(m.bias, 0)
|
| 200 |
+
nn.init.constant_(m.weight, 1.0)
|
| 201 |
+
elif isinstance(m, nn.Conv2d):
|
| 202 |
+
fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
|
| 203 |
+
fan_out //= m.groups
|
| 204 |
+
m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
|
| 205 |
+
if m.bias is not None:
|
| 206 |
+
m.bias.data.zero_()
|
| 207 |
+
|
| 208 |
+
def reset_drop_path(self, drop_path_rate):
|
| 209 |
+
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(self.depths))]
|
| 210 |
+
cur = 0
|
| 211 |
+
for i in range(self.depths[0]):
|
| 212 |
+
self.block1[i].drop_path.drop_prob = dpr[cur + i]
|
| 213 |
+
cur += self.depths[0]
|
| 214 |
+
for i in range(self.depths[1]):
|
| 215 |
+
self.block2[i].drop_path.drop_prob = dpr[cur + i]
|
| 216 |
+
cur += self.depths[1]
|
| 217 |
+
for i in range(self.depths[2]):
|
| 218 |
+
self.block3[i].drop_path.drop_prob = dpr[cur + i]
|
| 219 |
+
cur += self.depths[2]
|
| 220 |
+
for i in range(self.depths[3]):
|
| 221 |
+
self.block4[i].drop_path.drop_prob = dpr[cur + i]
|
| 222 |
+
|
| 223 |
+
def freeze_patch_emb(self):
|
| 224 |
+
self.patch_embed1.requires_grad = False
|
| 225 |
+
|
| 226 |
+
@torch.jit.ignore
|
| 227 |
+
def no_weight_decay(self):
|
| 228 |
+
return {'pos_embed1', 'pos_embed2', 'pos_embed3', 'pos_embed4', 'cls_token'}
|
| 229 |
+
|
| 230 |
+
def get_classifier(self):
|
| 231 |
+
return self.head
|
| 232 |
+
|
| 233 |
+
def reset_classifier(self, num_classes, global_pool=''):
|
| 234 |
+
self.num_classes = num_classes
|
| 235 |
+
self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity()
|
| 236 |
+
|
| 237 |
+
def forward_features(self, x):
|
| 238 |
+
B = x.shape[0]
|
| 239 |
+
outs = []
|
| 240 |
+
(x, H, W) = self.patch_embed1(x)
|
| 241 |
+
for (i, blk) in enumerate(self.block1):
|
| 242 |
+
x = blk(x, H, W)
|
| 243 |
+
x = self.norm1(x)
|
| 244 |
+
x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
|
| 245 |
+
outs.append(x)
|
| 246 |
+
(x, H, W) = self.patch_embed2(x)
|
| 247 |
+
for (i, blk) in enumerate(self.block2):
|
| 248 |
+
x = blk(x, H, W)
|
| 249 |
+
x = self.norm2(x)
|
| 250 |
+
x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
|
| 251 |
+
outs.append(x)
|
| 252 |
+
(x, H, W) = self.patch_embed3(x)
|
| 253 |
+
for (i, blk) in enumerate(self.block3):
|
| 254 |
+
x = blk(x, H, W)
|
| 255 |
+
x = self.norm3(x)
|
| 256 |
+
x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
|
| 257 |
+
outs.append(x)
|
| 258 |
+
(x, H, W) = self.patch_embed4(x)
|
| 259 |
+
for (i, blk) in enumerate(self.block4):
|
| 260 |
+
x = blk(x, H, W)
|
| 261 |
+
x = self.norm4(x)
|
| 262 |
+
x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
|
| 263 |
+
outs.append(x)
|
| 264 |
+
return outs
|
| 265 |
+
|
| 266 |
+
def forward(self, x):
|
| 267 |
+
x = self.forward_features(x)
|
| 268 |
+
return x
|
| 269 |
+
|
| 270 |
+
class DWConv(nn.Module):
|
| 271 |
+
|
| 272 |
+
def __init__(self, dim=768):
|
| 273 |
+
super(DWConv, self).__init__()
|
| 274 |
+
self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, bias=True, groups=dim)
|
| 275 |
+
|
| 276 |
+
def forward(self, x, H, W):
|
| 277 |
+
(B, N, C) = x.shape
|
| 278 |
+
x = x.transpose(1, 2).view(B, C, H, W)
|
| 279 |
+
x = self.dwconv(x)
|
| 280 |
+
x = x.flatten(2).transpose(1, 2)
|
| 281 |
+
return x
|
| 282 |
+
|
| 283 |
+
class mit_b0(MixVisionTransformer):
|
| 284 |
+
|
| 285 |
+
def __init__(self, in_chans=3, **kwargs):
|
| 286 |
+
super(mit_b0, self).__init__(patch_size=4, embed_dims=[32, 64, 160, 256], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4], qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-06), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1], drop_rate=0.0, drop_path_rate=0.1, in_chans=in_chans)
|
| 287 |
+
|
| 288 |
+
class mit_b1(MixVisionTransformer):
|
| 289 |
+
|
| 290 |
+
def __init__(self, in_chans=3, **kwargs):
|
| 291 |
+
super(mit_b1, self).__init__(patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4], qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-06), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1], drop_rate=0.0, drop_path_rate=0.1, in_chans=in_chans)
|
| 292 |
+
|
| 293 |
+
class mit_b2(MixVisionTransformer):
|
| 294 |
+
|
| 295 |
+
def __init__(self, in_chans=3, **kwargs):
|
| 296 |
+
super(mit_b2, self).__init__(patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4], qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-06), depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1], drop_rate=0.0, drop_path_rate=0.1, in_chans=in_chans)
|
| 297 |
+
|
| 298 |
+
class mit_b3(MixVisionTransformer):
|
| 299 |
+
|
| 300 |
+
def __init__(self, in_chans=3, **kwargs):
|
| 301 |
+
super(mit_b3, self).__init__(patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4], qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-06), depths=[3, 4, 18, 3], sr_ratios=[8, 4, 2, 1], drop_rate=0.0, drop_path_rate=0.1, in_chans=in_chans)
|
| 302 |
+
|
| 303 |
+
class mit_b4(MixVisionTransformer):
|
| 304 |
+
|
| 305 |
+
def __init__(self, in_chans=3, **kwargs):
|
| 306 |
+
super(mit_b4, self).__init__(patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4], qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-06), depths=[3, 8, 27, 3], sr_ratios=[8, 4, 2, 1], drop_rate=0.0, drop_path_rate=0.1, in_chans=in_chans)
|
| 307 |
+
|
| 308 |
+
class mit_b5(MixVisionTransformer):
|
| 309 |
+
|
| 310 |
+
def __init__(self, in_chans=3, **kwargs):
|
| 311 |
+
super(mit_b5, self).__init__(patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4], qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-06), depths=[3, 6, 40, 3], sr_ratios=[8, 4, 2, 1], drop_rate=0.0, drop_path_rate=0.1, in_chans=in_chans)
|
models/decoder/__init__.py
ADDED
|
File without changes
|