Spaces:
Running

lauransotomayor's picture
Mirror GitHub Pages presentation build (part 4)
d1ffd83 verified
|
Raw History Blame Contribute Delete
16.9 kB

Phase 2: Reference Data

Tools for converting manual annotations into rasterised fractional vegetation cover (FVC) labels registered to the Phase 1 tile grid.

Method

Manual annotations and spectral index thresholds were combined into multi-class label rasters matching the predictor tiles. The workflow involves:

  1. Deriving a bare-earth (BE) class from MSAVI/NDVI thresholds on stretched composites
  2. Converting LabelMe JSON annotations to georeferenced shapefiles
  3. Concatenating the BE class with the manually annotated classes
  4. Rasterising the merged vector labels to a single-band multi-class GeoTIFF
  5. Optionally masking out water and shadow
  6. Downsampling 1 cm labels to 5 cm and 10 cm by majority vote

Each class is represented by a unique integer in a single-band mask, so one raster carries the full schema per tile.

Label Quality Assessment

The 2D reference labels are foundational for the downstream experiments, so their quality should be assessed explicitly. Class frequency distributions are computed with 2_5_class_frecuency.py, and per-class spectral separability is inspected with 2_6_spectrum.py β€” classes that overlap spectrally are the ones most likely to be confused by the model.

A practical extension is an instance-level validation workflow that evaluates the reference annotations for agreement, highlights ambiguous or noisy regions, and produces a quantitative quality report before the labels are used for training. This could include per-class precision/recall/F1, confusion analysis, uncertainty estimates, and a manual review of the lowest-confidence samples to document the reliability of the 2D reference labels.

Contents

phase_2_reference_data/
β”œβ”€β”€ step_1_be_class/
β”‚   └── 1_3_be_class_msavi_ndvi.py           # BE class from MSAVI/NDVI β†’ MASK_BE.tif + .shp
β”œβ”€β”€ step_2_fvc_classes_combined/
β”‚   β”œβ”€β”€ 2_1_labelme_json_to_shpFormat.py     # LabelMe JSON β†’ shapefile
β”‚   β”œβ”€β”€ 2_2_concat_beClass_otherClasses.py   # Merge BE with annotated classes
β”‚   β”œβ”€β”€ 2_4_5c_gettingMultipleClasses.py     # Rasterise β†’ multi-class single-band GeoTIFF
β”‚   β”œβ”€β”€ 2_5_class_frecuency.py               # Class frequency distributions
β”‚   β”œβ”€β”€ 2_6_spectrum.py                      # Per-class spectral signatures
β”‚   β”œβ”€β”€ 2_6b_spectrum_tile25_ci_triangles.py # Spectral CI comparison
β”‚   └── 2_7_merge_shapefiles.py              # Merge shapefiles across tiles
β”œβ”€β”€ step_3_fvc_nowater/
β”‚   └── mask_out_water.py                    # Remove water class β†’ mask_fvc_nowater
β”œβ”€β”€ step_4_fvc_noshadow/
β”‚   └── mask_out_shadow.py                   # Remove shadow class β†’ mask_fvc_noshadow
└── step_5_downsampling_labels/
    β”œβ”€β”€ downsampling_labels.py               # Downsample labels
    β”œβ”€β”€ downsampling_labels_majvote.py       # Majority-vote downsampling (preferred)
    └── clip_masks_batch_256.py              # Batch clip masks to a sub-grid

Usage

All paths resolve through configs/paths.yaml β€” see docs/REPRODUCTION.md.

python utils/fvc_paths.py --check    # confirm the data roots resolve first

Steps 1–2: Build the label rasters

python phase_2_reference_data/step_1_be_class/1_3_be_class_msavi_ndvi.py
python phase_2_reference_data/step_2_fvc_classes_combined/2_1_labelme_json_to_shpFormat.py
python phase_2_reference_data/step_2_fvc_classes_combined/2_2_concat_beClass_otherClasses.py
python phase_2_reference_data/step_2_fvc_classes_combined/2_4_5c_gettingMultipleClasses.py

Direct Shapefile/GeoPackage conversion with MSAVI-derived BE

Use rasterize_fvc_labels.py for an existing polygon annotation layer. It reads the class attribute case-insensitively (be, npv, pv) and writes one signed int8 band: BE=0, NPV=1, PV=2, ignore/NoData=-1. Unknown classes, invalid geometries, missing CRS and existing output files raise errors rather than silently dropping labels or overwriting results.

BE is derived using the first MSAVI workflow in 1_3_be_class_msavi_ndvi.py: MSAVI at or below (2*mean + median)/3, rounded half-up to two decimal places over valid pixels. Manual polygons then overwrite the derived labels, with fixed priority NPV > PV > BE, independent of vector feature order. Valid pixels without derived BE or a manual annotation remain -1; they are not automatically labelled NPV. Reference NoData stays ignored even under polygons.

The output preserves the reference CRS, transform and dimensions exactly. Vectors are reprojected to that CRS, and rasterization uses pixel-centre coverage (all_touched=False). Specify 1-based NIR and Red band numbers explicitly; the old script's band 10/6 assumption is not used.

For the site-2 tile-8 stretched false-colour composite (NIR/Red/Blue):

python phase_2_reference_data/step_2_fvc_classes_combined/rasterize_fvc_labels.py \
  --vector /home/laura/Documents/data_model/annotation_site2_SASMDD0013/composites_mica_5cm/mica05_labels/SASMDD0013_20240310_mica05_tiles8.gpkg \
  --reference /home/laura/Documents/data_model/annotation_site2_SASMDD0013/composites_mica_5cm/composite_percentile_tiles_multispectral_8.tif \
  --nir-band 1 --red-band 2 \
  --output /home/laura/Documents/data_model/annotation_site2_SASMDD0013/composites_mica_5cm/mica05_labels/SASMDD0013_20240310_mica05_tiles8_fvc_msavi.tif

Use --layer NAME for a specific GeoPackage layer, or --class-field NAME for a different label attribute. These paths are explicit CLI inputs; no configured dataset paths are changed.

Batch mode loops over every *_tilesN.gpkg/.shp in --vector-dir, pairs it with --reference-template (default composite_percentile_tiles_multispectral_{tile}.tif) in --reference-dir, and writes <vector stem>_fvc_msavi.tif to --output-dir (default: the vector folder). It stops before writing anything if any vector has no matching reference. Add --overwrite to replace existing outputs.

D=/home/laura/Documents/data_model/annotation_site2_SASMDD0013/composites_mica_5cm
python phase_2_reference_data/step_2_fvc_classes_combined/rasterize_fvc_labels.py \
  --vector-dir $D/mica05_labels --reference-dir $D \
  --nir-band 1 --red-band 2

To reduce derived BE coverage, use --be-offset. It lowers the rounded MSAVI threshold above by a fixed amount, so BE becomes MSAVI <= round_half_up((2*mean + median)/3, 2) - offset. The default 0 preserves the original masks. Manual BE, NPV and PV polygons still take precedence (NPV > PV > BE). Removed BE pixels become ignored (-1), not automatically vegetation. Save a comparison batch separately so the original masks remain available:

D=/home/laura/Documents/data_model/annotation_site2_SASMDD0013/composites_mica_5cm
python phase_2_reference_data/step_2_fvc_classes_combined/rasterize_fvc_labels.py \
  --vector-dir $D/mica05_labels --reference-dir $D \
  --output-dir $D/mica05_labels/msavi_offset_005 \
  --nir-band 1 --red-band 2 --be-offset 0.05

For these five composites, 0.05 reduces final-label BE coverage from 66.7% to about 51.5% of each 608 x 608 tile, with manual NPV/PV unchanged. The offset and final threshold are recorded in the output tags.

Caution: independently stretched 8-bit bands do not preserve reflectance ratios. The example reproduces the requested composite-based MSAVI workflow, not a calibrated reflectance-based vegetation index. Prefer unstretched reflectance inputs for physically interpretable index thresholds. The computed threshold and input paths are recorded in the output tags.

Focused regression tests (run from the repository root):

python -m unittest discover -s phase_2_reference_data/step_2_fvc_classes_combined/tests -v

Steps 3–4: Optional masking

python phase_2_reference_data/step_3_fvc_nowater/mask_out_water.py
python phase_2_reference_data/step_4_fvc_noshadow/mask_out_shadow.py

Step 5: Downsampling

bash scripts/downsample_site1_labels_low_offset.sh    # 1 cm β†’ 5 cm, majority vote

Quality checks

python phase_2_reference_data/step_2_fvc_classes_combined/2_5_class_frecuency.py
python phase_2_reference_data/step_2_fvc_classes_combined/2_6_spectrum.py

FVC Classification Scheme

Class IDs:

  • ID 0: BE β€” bare earth
  • ID 1: NPV β€” non-photosynthetic vegetation
  • ID 2: PV β€” photosynthetic vegetation
  • ID 3: SI β€” shadow (extended schema only)
  • ID 4: WI β€” water (extended schema only)

Density profiles select the schema:

Profile Classes
low BE, NPV, PV
medium BE, NPV, PV, SI
dense BE, NPV, PV, SI, WI

Extended at runtime without editing code:

FVC_EXTRA_CLASS_LABELS="SI"       # + shadow = 3
FVC_EXTRA_CLASS_LABELS="SI,WI"    # + shadow = 3, water = 4

Ignored value: pixels outside valid annotation extents are mapped to -1 (training ignore index). Majority-vote outputs preserve the explicit source NoData value where present; disagreement maps use 255 as their NoData/legend value.

Downsampling

1 cm labels are downsampled to 5 cm and 10 cm by majority vote (modal class within each output pixel footprint), not nearest-neighbour β€” nearest-neighbour would discard the sub-pixel class mixture that defines fractional cover at coarser resolutions.

Downsampling preserves grid origin and alignment, so 5 cm and 10 cm labels stay registered to the predictor tiles produced in Phase 1. This is why the tiles_3070 grid exists: 3070 px at 1 cm divides evenly into 614 px at 5 cm and 307 px at 10 cm.

Site-2 MicaSense: annotated 5 cm labels to aligned 10 cm masks

Downsample the latest msavi_offset_005 labels to the matching 304 px MicaSense predictor grids, preserving int8 and ignore/NoData -1:

D=/home/laura/Documents/data_model/annotation_site2_SASMDD0013/composites_mica_5cm/mica05_labels/msavi_offset_005
INPUT_DIR=$D \
OUTPUT_DIR=$D/downsample_10cm_mode_mica_304px \
REFERENCE_DIR=/home/laura/Documents/data_model/predictors/site2_SASMDD0013/mica_10/tiles_multispectral_int16_envi_304px \
SITE_NAME=SASMDD0013_Mica_5cm_to_10cm \
TARGET_RESOLUTION=0.1 \
RESAMPLING_METHOD=mode \
OUTPUT_PREFIX=mask_tiles_multispectral \
REQUIRE_REFERENCE=1 \
VALIDATE_GRID=1 \
RUN_CHAINED_COMPARISON=0 \
python phase_2_reference_data/step_5_downsampling_labels/downsampling_labels_majvote.py

The script recognises *_tilesN_fvc_msavi.tif as well as the older mask names. Outputs are mask_tiles_multispectral_N.tif, with the reference CRS, transform and dimensions. For north-up, same-CRS grids sharing exact bounds and integer scale factors, it uses GDAL's direct mode resampling instead of a warp: this avoids floating-point transforms accidentally including neighbouring rows/columns in otherwise exact 2 x 2 votes. Other alignments retain the GDAL warp path.

Votes exclude -1; all-ignored blocks remain -1. Ties use GDAL's first-class-to-reach-the-highest-count rule, not an additional NPV priority. NPV-over-PV polygon priority is already encoded in the 5 cm source masks.

Regression test:

python -m unittest discover -s phase_2_reference_data/step_5_downsampling_labels/tests -v

Site-2 FX10/FX17 hyperspectral: 10 cm masks and 152 px crops

Use the site-2 hyperspectral 304 px tiles as the footprint (the predictors/hyspec/... folders are site-1, EPSG:32754, and do not overlap):

A=/home/laura/Documents/data_model/annotation_site2_SASMDD0013
P=/home/laura/Documents/data_model/predictors/site2_SASMDD0013/hyspec
M304=$A/composites_hyspec_10cm/downsample_10cm_mode_fx10_fx17_215_trim_from_5cm_304
M152=$A/composites_hyspec_10cm/downsample_10cm_mode_fx10_fx17_215_trim_from_5cm_152_crop304_ov76

INPUT_DIR=$A/composites_mica_5cm/mica05_labels/msavi_offset_005 \
OUTPUT_DIR=$M304 \
REFERENCE_DIR=$P/FX10_FX17_215_trim_envi_304px \
SITE_NAME=site2_SASMDD0013 TARGET_RESOLUTION=0.1 RESAMPLING_METHOD=mode \
OUTPUT_PREFIX=mask_tiles_hyperspectral REQUIRE_REFERENCE=1 VALIDATE_GRID=1 \
RUN_CHAINED_COMPARISON=0 \
python phase_2_reference_data/step_5_downsampling_labels/downsampling_labels_majvote.py

python phase_3_models/unet_site_models/dataset/export_nonoverlap_pairs.py \
  --image-dir $P/FX10_FX17_215_trim_envi_304px --mask-dir $M304 \
  --out-image-dir $P/FX10_FX17_215_trim_envi_152_crop304_ov76 --out-mask-dir $M152 \
  --size 152 --overlap 76 --image-format ENVI --fail-on-padding \
  --metadata-csv $M152/patch_metadata.csv

This gives 3 x 3 crops per tile (*_rRR_cCC, 76 px stride) with identical predictor/mask transforms. Predictor crops keep the source nodata (-1) values. Crops exported before this fix (including site-1 FX10_FX17_215_trim_envi_152_crop304_ov76) stored in-bounds -1 as 0, because rasterio applies fill_value to nodata even for non-boundless reads.

Direct 1 cm β†’ 10 cm sensitivity check

For the hyperspectral U-Net masks, the preferred final 10 cm labels are produced directly from the original 1 cm annotations with majority vote. The previous staged workflow, 1 cm β†’ 5 cm β†’ 10 cm, is useful for co-registration with intermediate products, but sequential majority votes are not strictly associative. Therefore, the two pathways should be compared on the same final grid before concluding whether the staged pathway affects the labels.

Use the chained 10 cm masks as both the comparison target and the alignment reference when the predictor reference directory is incomplete. This ensures the direct 1 cm β†’ 10 cm outputs are generated on the same 304 px grid as the chained masks:

INPUT_DIR=/mnt/f/calperumResearch/site1_1_DD0001/inputs/masks/mask_fvc_noshadow/annotation_raster_1cm_clean \
OUTPUT_DIR=/mnt/f/calperumResearch/site1_1_DD0001/inputs/masks/fvc_class/downsample_10cm_mode_fx10_fx17_from_1cm_aligned_to_chained_304px \
CHAINED_COMPARISON_DIR=/mnt/f/calperumResearch/site1_1_DD0001/inputs/masks/fvc_class/downsample_10cm_mode_fx10_fx17_from_5cm_304px \
REFERENCE_DIR=/mnt/f/calperumResearch/site1_1_DD0001/inputs/masks/fvc_class/downsample_10cm_mode_fx10_fx17_from_5cm_304px \
TARGET_RESOLUTION=0.1 \
RESAMPLING_METHOD=mode \
OUTPUT_PREFIX=mask_tiles_hyperspectral \
RUN_CHAINED_COMPARISON=1 \
WRITE_DISAGREEMENT_MAPS=1 \
COMPARISON_CLASS_LABELS="BE:0,NPV:1,PV:2" \
/home/uqlsoto1/micromamba/envs/fvc_function/bin/python \
phase_2_reference_data/step_5_downsampling_labels/downsampling_labels_majvote.py

Validated DD0001 FX10/FX17 sensitivity results for the matched 304 px masks:

Metric Result
Compared tiles 5
Valid pixels compared 292,967
Pixel agreement 99.228%
Disagreement 0.772%
Class IoU Direct proportion Chained proportion Chained - direct
BE (0) 98.727% 54.638% 54.597% -0.041 pp
NPV (1) 93.963% 6.927% 6.946% +0.019 pp
PV (2) 98.932% 38.435% 38.457% +0.022 pp

These results show that the chained pathway introduces only small boundary-level differences for the matched tiles. The aggregate class-proportion shifts are below 0.05 percentage points for all three FVC classes.

Dependencies

mamba env create -f environment.yml && mamba activate fvc_function

Core requirements: rasterio, geopandas, shapely, fiona, gdal (osgeo), numpy, pandas.

Manual annotation is performed in LabelMe (JSON output) and QGIS; neither is part of this environment.

Outputs

  • Vector labels: per-tile shapefiles with class attributes
  • Raster labels: single-band multi-class GeoTIFF masks matching tile dimensions
  • Masked variants: mask_fvc_nowater/, mask_fvc_noshadow/
  • Downsampled labels: downsample_5cm_mode_multispec/, downsample_10cm_mode_fx10_*/
  • Quality reports: class frequency tables, per-class spectral signature plots

Notes

Label folder names encode their provenance β€” mask_fvc_noshadow/manual_gt_infer/downsample_5cm_mode_multispec_304_crop608_ov152 reads as: shadow removed, manual ground truth, downsampled to 5 cm by mode, on the 304 px crop-608 overlap-152 grid. Matching a predictor folder to its label folder means matching that grid suffix.

Related documentation: