Skip to content

samstars.training.records

samstars.training.records

Build StarDist training records from proposal rasters and crown labels.

build_stardist_training_records(*, proposal_records, tiles_dir, out_dir, val_fraction=0.2, seed=42)

Build train/val StarDist records from proposal rasters and labeled tiles.

Source code in samstars/training/records.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
def build_stardist_training_records(
    *,
    proposal_records: Path,
    tiles_dir: Path,
    out_dir: Path,
    val_fraction: float = 0.2,
    seed: int = 42,
) -> tuple[Path, Path]:
    """Build train/val StarDist records from proposal rasters and labeled tiles."""
    proposal_records = Path(proposal_records)
    tiles_dir = Path(tiles_dir)
    out_dir = Path(out_dir)
    masks_dir = out_dir / "masks"
    masks_dir.mkdir(parents=True, exist_ok=True)

    base_records = json.load(open(proposal_records))
    records: list[dict] = []
    for rec in base_records:
        stem = _proposal_stem(rec)
        tile_name = _tile_name_from_stem(stem)
        crowns_path = tiles_dir / tile_name / "crowns.gpkg"
        if not crowns_path.exists():
            continue

        reference_value = rec.get("index") or rec.get("file_name") or rec.get("logit") or ""
        reference = _resolve_record_path(reference_value, proposal_records)
        if not reference.exists():
            continue

        mask_path = masks_dir / f"{stem}_mask.tif"
        if not mask_path.exists():
            ok = _rasterize_crowns(crowns_path, reference, mask_path)
            if not ok:
                continue

        out_rec = dict(rec)
        for key in ("file_name", "chm", "cost", "logit", "index"):
            if out_rec.get(key):
                out_rec[key] = str(_resolve_record_path(out_rec[key], proposal_records).resolve())
        out_rec["mask"] = str(mask_path.resolve())
        records.append(out_rec)

    rng = random.Random(seed)
    rng.shuffle(records)

    if len(records) <= 1 or val_fraction <= 0:
        train_records = records
        val_records = []
    else:
        n_val = max(1, int(round(len(records) * val_fraction)))
        n_val = min(n_val, len(records) - 1)
        val_records = records[:n_val]
        train_records = records[n_val:]

    train_path = out_dir / "train_records.json"
    val_path = out_dir / "val_records.json"
    json.dump(train_records, open(train_path, "w"))
    json.dump(val_records, open(val_path, "w"))
    print(f"✓ wrote {train_path} ({len(train_records)} records)")
    print(f"✓ wrote {val_path} ({len(val_records)} records)")
    return train_path, val_path

main()

Run the command-line entry point.

Source code in samstars/training/records.py
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
def main() -> None:
    """Run the command-line entry point."""
    parser = argparse.ArgumentParser(description="Build StarDist training records from proposal rasters and crown labels.")
    parser.add_argument("--proposal-records", type=Path, required=True, help="Proposal-record JSON produced by SAM proposals")
    parser.add_argument("--tiles-dir", type=Path, required=True, help="Prepared tile directory containing crowns.gpkg labels")
    parser.add_argument("--out-dir", type=Path, required=True, help="Directory to write masks and train/val record JSON files")
    parser.add_argument("--val-fraction", type=float, default=0.2, help="Fraction of records to reserve for validation")
    parser.add_argument("--seed", type=int, default=42, help="Random seed for the train/val split")
    args = parser.parse_args()

    build_stardist_training_records(
        proposal_records=args.proposal_records,
        tiles_dir=args.tiles_dir,
        out_dir=args.out_dir,
        val_fraction=args.val_fraction,
        seed=args.seed,
    )