Skip to content

samstars.api

samstars.api

Top-level runtime API for samstars.

SamStars

Load a trained bundle and reuse its model files and stored defaults.

Parameters:

Name Type Description Default
model Path

Bundle directory containing manifest.json and the trained artifacts.

required

Use train to create a bundle and segment to apply it to source rasters or prepared tiles. Instance methods accept the same processing controls as the top-level functions.

Source code in samstars/api.py
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
class SamStars:
    """Load a trained bundle and reuse its model files and stored defaults.

    Args:
        model: Bundle directory containing manifest.json and the trained artifacts.

    Use `train` to create a bundle and `segment` to apply it to source rasters
    or prepared tiles. Instance methods accept the same processing controls as
    the top-level functions.
    """

    def __init__(self, model: Path):
        self.root = Path(model)
        self.manifest_path = _bundle_manifest_path(self.root)
        if not self.manifest_path.exists():
            raise FileNotFoundError(f"Missing model bundle manifest: {self.manifest_path}")
        self.root = self.manifest_path.parent
        self.manifest = json.load(open(self.manifest_path))
        if self.manifest.get("bundle_format") != _BUNDLE_FORMAT:
            raise ValueError(f"Unsupported model bundle format in {self.manifest_path}")

        self.decoder_path = self.root / self.manifest["decoder"]
        self.config_path = self.root / self.manifest["config"]
        self.weights_path = self.root / self.manifest["weights"]
        thresholds_name = self.manifest.get("thresholds")
        self.thresholds_path = self.root / thresholds_name if thresholds_name else None

        if not self.decoder_path.exists():
            raise FileNotFoundError(f"Missing decoder checkpoint: {self.decoder_path}")
        if not self.config_path.exists():
            raise FileNotFoundError(f"Missing StarDist config: {self.config_path}")
        if not self.weights_path.exists():
            raise FileNotFoundError(f"Missing StarDist weights: {self.weights_path}")

        self.defaults = self.manifest.get("defaults", {})

    @classmethod
    def load(cls, model: Path | SamStars) -> SamStars:
        """Load a model bundle or return an existing SamStars object."""
        if isinstance(model, cls):
            return model
        return cls(Path(model))

    @staticmethod
    def _load_stardist_thresholds_from_dir(model_dir: Path) -> tuple[float | None, float | None]:
        """Read optimized StarDist thresholds when available."""
        thresholds_path = Path(model_dir) / "thresholds.json"
        if not thresholds_path.exists():
            return None, None
        data = json.load(open(thresholds_path))
        prob = data.get("prob")
        nms = data.get("nms")
        if prob is None:
            prob = data.get("prob_thresh")
        if nms is None:
            nms = data.get("nms_thresh")
        return prob, nms

    @staticmethod
    @contextmanager
    def _work_root(out: Path, storage: str, *, prefix: str) -> Iterator[Path]:
        """Yield the working root for a train or segment run."""
        storage = _normalize_storage(storage)
        out = Path(out)
        out.mkdir(parents=True, exist_ok=True)
        if storage == "persistent":
            yield out
            return

        with tempfile.TemporaryDirectory(prefix=prefix) as td:
            yield Path(td)

    @staticmethod
    def _write_bundle_manifest(
        *,
        out: Path,
        defaults: dict[str, Any],
    ) -> Path:
        """Write the model-bundle manifest."""
        thresholds_name = "thresholds.json" if (out / "thresholds.json").exists() else None
        manifest = {
            "bundle_format": _BUNDLE_FORMAT,
            "bundle_version": _BUNDLE_VERSION,
            "decoder": "decoder.pth",
            "config": "config.json",
            "thresholds": thresholds_name,
            "weights": "weights.h5",
            "defaults": defaults,
        }
        manifest_path = out / _BUNDLE_MANIFEST
        json.dump(manifest, open(manifest_path, "w"), indent=2)
        return manifest_path

    @staticmethod
    def _write_run_manifest(
        *,
        out: Path,
        storage: str,
        model: SamStars,
        work_dir: Path | None,
    ) -> Path:
        """Write a lightweight run manifest for segmentation outputs."""
        manifest = {
            "bundle_format": "samstars_run",
            "bundle_version": 1,
            "storage": storage,
            "model_bundle": str(model.root),
            "work_dir": str(work_dir) if work_dir is not None else None,
            "crowns": str(out / "crowns" / "crowns.gpkg"),
            "labels_dir": str(out / "labels") if (out / "labels").exists() else None,
        }
        path = out / _BUNDLE_MANIFEST
        json.dump(manifest, open(path, "w"), indent=2)
        return path

    @staticmethod
    def _finalize_temp_outputs(
        *,
        temp_root: Path,
        out: Path,
    ) -> None:
        """Copy final user-facing outputs from a temp run root to the durable out directory."""
        crowns_src = temp_root / "crowns"
        labels_src = temp_root / "labels"
        crowns_dst = out / "crowns"
        labels_dst = out / "labels"

        if crowns_dst.exists():
            shutil.rmtree(crowns_dst)
        if crowns_src.exists():
            shutil.copytree(crowns_src, crowns_dst)

        if labels_dst.exists():
            shutil.rmtree(labels_dst)
        if labels_src.exists():
            shutil.copytree(labels_src, labels_dst)

    def _stage_stardist_model(self, stage_root: Path) -> Path:
        """Create the temporary StarDist directory used by refinement."""
        model_root = stage_root / "stardist_model"
        nested = model_root / "stardist"
        nested.mkdir(parents=True, exist_ok=True)
        _copy_or_symlink(self.config_path, nested / "config.json")
        _copy_or_symlink(self.weights_path, nested / "weights_best.h5")
        if self.thresholds_path is not None and self.thresholds_path.exists():
            _copy_or_symlink(self.thresholds_path, nested / "thresholds.json")
        return nested

    @classmethod
    def train(
        cls,
        *,
        tiles_dir: Path | None = None,
        img: Path | None = None,
        chm: Path | None = None,
        den: Path | None = None,
        crowns: Path | None = None,
        sam_base_ckpt: Path,
        out: Path,
        storage: str,
        rgb_bands: tuple[int, int, int] | None = None,
        nir_band: int | None = None,
        texture_band: int | None = None,
        device: str = "cpu",
        chip_size: int = 512,
        chip_stride: int = 384,
        sam_epochs: int = 15,
        sam_min_iters: int = 0,
        sam_lr: float = 5e-5,
        fg_extra: int = DEFAULT_FG_EXTRA,
        stardist_epochs: int = 50,
        stardist_min_iters: int = 0,
        val_fraction: float = 0.2,
        crop_smooth_sigma: float = 2.0,
        smooth_sigma: float = 4.0,
        post_smooth_sigma: float = 0.0,
        thin_seeds: bool = True,
        thin_dist: float = 0.8,
        seed_d_min: float = 4.5,
        seed_min_dist_px: int = 4,
        seed_gauss_sigma: int = 2,
        seed_min_samples: int = 1,
        seed_merge_radius: float = 3.0,
        seed_min_canopy_height: float = 2.0,
        stardist_input_key: str = "index",
        stardist_use_aux: bool = True,
        stardist_normalize_inputs: bool = True,
        stardist_augment: bool = True,
        stardist_window_size_m: float | None = None,
        stardist_window_overlap_m: float = 0.0,
        stardist_dedup_iou_thr: float = 0.0,
        stardist_cpu: bool = False,
        fast: bool = False,
    ) -> SamStars:
        """Train a model bundle; fg_extra controls extra foreground prompts (0 = seed only)."""
        fg_extra = validate_fg_extra(fg_extra)
        from samstars.data import build_scale_stats_from_proposal_records
        from samstars.segmentation.engine import run_segmentation
        from samstars.training.chips import build_training_chips
        from samstars.training.records import build_stardist_training_records
        from samstars.training.sam_training import train_decoder

        storage = _normalize_storage(storage)
        out = Path(out)
        out.mkdir(parents=True, exist_ok=True)
        for stale in (
            out / "decoder.pth",
            out / "config.json",
            out / "weights.h5",
            out / "thresholds.json",
            out / _BUNDLE_MANIFEST,
        ):
            if stale.exists():
                stale.unlink()

        with cls._work_root(out, storage, prefix="samstars-train-") as work_root:
            training_root = work_root / "_training" if storage == "persistent" else work_root
            prep_root = training_root / "prep"
            training_chips_dir = training_root / "training_chips"
            training_run_dir = training_root / "training_run"
            records_dir = training_root / "stardist_training_records"
            scale_stats = training_root / "training_scale_stats.json"
            stardist_train_root = training_root / "_stardist_model"

            decoder_path = out / "decoder.pth"
            training_tiles_dir = _resolve_training_tiles(
                tiles_dir=tiles_dir,
                img=img,
                chm=chm,
                den=den,
                crowns=crowns,
                rgb_bands=rgb_bands,
                nir_band=nir_band,
                texture_band=texture_band,
                prep_root=prep_root,
                thin_seeds=thin_seeds,
                thin_dist=thin_dist,
                seed_d_min=seed_d_min,
                seed_min_dist_px=seed_min_dist_px,
                seed_gauss_sigma=seed_gauss_sigma,
                seed_min_samples=seed_min_samples,
                seed_merge_radius=seed_merge_radius,
                seed_min_canopy_height=seed_min_canopy_height,
            )

            build_training_chips(
                tiles_dir=training_tiles_dir,
                out_dir=training_chips_dir,
                chip_size=chip_size,
                stride=chip_stride,
            )

            train_decoder(
                chip_dir=training_chips_dir,
                ckpt=Path(sam_base_ckpt),
                out_path=decoder_path,
                epochs=sam_epochs,
                min_iters=sam_min_iters,
                lr=sam_lr,
                device=device,
                fg_extra=fg_extra,
            )

            proposal_result = run_segmentation(
                tiles_dir=training_tiles_dir,
                out_dir=training_run_dir,
                sam_ckpt=decoder_path,
                device=device,
                run_sam=True,
                run_stardist=False,
                fast=fast,
                fg_extra=fg_extra,
                crop_smooth_sigma=crop_smooth_sigma,
                smooth_sigma=smooth_sigma,
                post_smooth_sigma=post_smooth_sigma,
            )

            train_records, val_records = build_stardist_training_records(
                proposal_records=proposal_result["proposal_records"],
                tiles_dir=training_tiles_dir,
                out_dir=records_dir,
                val_fraction=val_fraction,
            )

            build_scale_stats_from_proposal_records(
                proposal_records=proposal_result["proposal_records"],
                out=scale_stats,
                percentiles=(2.0, 98.0),
                chm_key="chm",
                nodata_values=(-9999.0,),
            )

            if stardist_cpu:
                cmd = [
                    sys.executable,
                    str(Path(__file__).resolve().parent / "training" / "stardist_training.py"),
                    "--train-records",
                    str(train_records),
                    "--val-records",
                    str(val_records),
                    "--out-dir",
                    str(stardist_train_root),
                    "--model-name",
                    "stardist",
                    "--epochs",
                    str(stardist_epochs),
                    "--min-iters",
                    str(stardist_min_iters),
                    "--input-key",
                    stardist_input_key,
                ]
                if stardist_use_aux:
                    cmd.extend(["--use-aux", "--scale-stats", str(scale_stats)])
                if not stardist_normalize_inputs:
                    cmd.append("--no-normalize")
                if not stardist_augment:
                    cmd.append("--no-augment")
                env = dict(os.environ)
                env["CUDA_VISIBLE_DEVICES"] = ""
                subprocess.run(cmd, check=True, env=env)
            else:
                from samstars.training.stardist_training import train_stardist_model

                train_stardist_model(
                    train_records=train_records,
                    val_records=val_records,
                    out_dir=stardist_train_root,
                    model_name="stardist",
                    epochs=stardist_epochs,
                    min_iters=stardist_min_iters,
                    input_key=stardist_input_key,
                    use_aux=stardist_use_aux,
                    scale_stats_path=scale_stats if stardist_use_aux else None,
                    normalize_inputs=stardist_normalize_inputs,
                    augment=stardist_augment,
                )

            stardist_dir = stardist_train_root / "stardist"
            shutil.copy2(stardist_dir / "config.json", out / "config.json")
            weight_path = _find_stardist_weight(stardist_dir)
            shutil.copy2(weight_path, out / "weights.h5")
            if (stardist_dir / "thresholds.json").exists():
                shutil.copy2(stardist_dir / "thresholds.json", out / "thresholds.json")
            elif (out / "thresholds.json").exists():
                (out / "thresholds.json").unlink()

        prob_thr, nms_thr = cls._load_stardist_thresholds_from_dir(out)
        cls._write_bundle_manifest(
            out=out,
            defaults={
                "rgb_bands": list(rgb_bands) if rgb_bands is not None else [1, 2, 3],
                "nir_band": nir_band,
                "texture_band": texture_band,
                "stardist_input_key": stardist_input_key,
                "stardist_use_aux": stardist_use_aux,
                "stardist_prob_thr": prob_thr,
                "stardist_nms_thr": nms_thr,
                "stardist_window_size_m": stardist_window_size_m,
                "stardist_window_overlap_m": stardist_window_overlap_m,
                "stardist_dedup_iou_thr": stardist_dedup_iou_thr,
                "stardist_cpu": stardist_cpu,
                "crop_smooth_sigma": crop_smooth_sigma,
                "smooth_sigma": smooth_sigma,
                "post_smooth_sigma": post_smooth_sigma,
                "fast": fast,
                "fg_extra": fg_extra,
            },
        )
        return cls(out)

    def segment(
        self,
        *,
        out: Path,
        storage: str,
        tiles_dir: Path | None = None,
        img: Path | None = None,
        chm: Path | None = None,
        den: Path | None = None,
        rgb_bands: tuple[int, int, int] | None = None,
        nir_band: int | None = None,
        texture_band: int | None = None,
        device: str = "cpu",
        stardist_input_key: str | None = None,
        stardist_use_aux: bool | None = None,
        stardist_prob_thr: float | None = None,
        stardist_nms_thr: float | None = None,
        stardist_window_size_m: float | None = None,
        stardist_window_overlap_m: float | None = None,
        stardist_dedup_iou_thr: float | None = None,
        stardist_cpu: bool = False,
        stardist_resume: bool = False,
        stardist_resume_from_labels: bool = False,
        stardist_skip_sources: str | None = None,
        stardist_skip_sources_file: Path | None = None,
        run_sam: bool = True,
        run_stardist: bool = True,
        skip_existing_sam: bool = True,
        log_refinement: bool = False,
        fast: bool | None = None,
        fg_extra: int | None = None,
        crop_smooth_sigma: float | None = None,
        smooth_sigma: float | None = None,
        post_smooth_sigma: float | None = None,
    ) -> SamStarsResult:
        """Run segmentation; fg_extra=None reuses the bundle count (80 for older bundles)."""
        resolved_fg_extra = validate_fg_extra(
            self.defaults.get("fg_extra", DEFAULT_FG_EXTRA) if fg_extra is None else fg_extra
        )
        from samstars.segmentation.engine import run_segmentation

        storage = _normalize_storage(storage)
        out = Path(out)
        if out.resolve() == self.root.resolve():
            raise ValueError("out must be different from the model bundle directory.")
        out.mkdir(parents=True, exist_ok=True)

        resolved_rgb_bands = rgb_bands
        if resolved_rgb_bands is None and self.defaults.get("rgb_bands") is not None:
            resolved_rgb_bands = tuple(self.defaults["rgb_bands"])
        resolved_nir_band = self.defaults.get("nir_band") if nir_band is None else nir_band
        resolved_texture_band = self.defaults.get("texture_band") if texture_band is None else texture_band

        resolved_stardist_input_key = stardist_input_key or self.defaults.get("stardist_input_key", "index")
        resolved_stardist_use_aux = (
            bool(self.defaults.get("stardist_use_aux", True))
            if stardist_use_aux is None
            else stardist_use_aux
        )
        resolved_prob_thr = self.defaults.get("stardist_prob_thr") if stardist_prob_thr is None else stardist_prob_thr
        resolved_nms_thr = self.defaults.get("stardist_nms_thr") if stardist_nms_thr is None else stardist_nms_thr
        resolved_window_size_m = (
            self.defaults.get("stardist_window_size_m")
            if stardist_window_size_m is None
            else stardist_window_size_m
        )
        resolved_window_overlap_m = (
            self.defaults.get("stardist_window_overlap_m", 0.0)
            if stardist_window_overlap_m is None
            else stardist_window_overlap_m
        )
        resolved_dedup_iou_thr = (
            self.defaults.get("stardist_dedup_iou_thr", 0.0)
            if stardist_dedup_iou_thr is None
            else stardist_dedup_iou_thr
        )
        resolved_fast = bool(self.defaults.get("fast", False)) if fast is None else fast
        resolved_crop_sigma = (
            float(self.defaults.get("crop_smooth_sigma", 2.0))
            if crop_smooth_sigma is None
            else crop_smooth_sigma
        )
        resolved_smooth_sigma = (
            float(self.defaults.get("smooth_sigma", 4.0))
            if smooth_sigma is None
            else smooth_sigma
        )
        resolved_post_sigma = (
            float(self.defaults.get("post_smooth_sigma", 0.0))
            if post_smooth_sigma is None
            else post_smooth_sigma
        )

        with self._work_root(out, storage, prefix="samstars-segment-") as work_root:
            with tempfile.TemporaryDirectory(prefix="samstars-stardist-") as model_stage:
                staged_stardist = self._stage_stardist_model(Path(model_stage))
                run_info = run_segmentation(
                    tiles_dir=tiles_dir,
                    img=img,
                    chm=chm,
                    den=den,
                    rgb_bands=resolved_rgb_bands,
                    nir_band=resolved_nir_band,
                    texture_band=resolved_texture_band,
                    out_dir=work_root,
                    sam_ckpt=self.decoder_path,
                    device=device,
                    stardist_model=staged_stardist,
                    stardist_input_key=resolved_stardist_input_key,
                    stardist_use_aux=resolved_stardist_use_aux,
                    stardist_prob_thr=resolved_prob_thr,
                    stardist_nms_thr=resolved_nms_thr,
                    stardist_window_size_m=resolved_window_size_m,
                    stardist_window_overlap_m=float(resolved_window_overlap_m or 0.0),
                    stardist_dedup_iou_thr=float(resolved_dedup_iou_thr or 0.0),
                    stardist_cpu=stardist_cpu,
                    stardist_resume=stardist_resume,
                    stardist_resume_from_labels=stardist_resume_from_labels,
                    stardist_skip_sources=stardist_skip_sources,
                    stardist_skip_sources_file=stardist_skip_sources_file,
                    run_sam=run_sam,
                    run_stardist=run_stardist,
                    skip_existing_sam=skip_existing_sam,
                    log_refinement=log_refinement,
                    fast=resolved_fast,
                    fg_extra=resolved_fg_extra,
                    crop_smooth_sigma=resolved_crop_sigma,
                    smooth_sigma=resolved_smooth_sigma,
                    post_smooth_sigma=resolved_post_sigma,
                )

            if storage == "temp":
                self._finalize_temp_outputs(temp_root=work_root, out=out)
                work_dir = None
            else:
                work_dir = work_root

        self._write_run_manifest(
            out=out,
            storage=storage,
            model=self,
            work_dir=work_dir,
        )
        labels_dir = out / "labels" if (out / "labels").exists() else None
        return SamStarsResult(
            out=out,
            crowns=out / "crowns" / "crowns.gpkg",
            labels_dir=labels_dir,
            storage=storage,
            work_dir=work_dir,
        )

load(model) classmethod

Load a model bundle or return an existing SamStars object.

Source code in samstars/api.py
253
254
255
256
257
258
@classmethod
def load(cls, model: Path | SamStars) -> SamStars:
    """Load a model bundle or return an existing SamStars object."""
    if isinstance(model, cls):
        return model
    return cls(Path(model))

segment(*, out, storage, tiles_dir=None, img=None, chm=None, den=None, rgb_bands=None, nir_band=None, texture_band=None, device='cpu', stardist_input_key=None, stardist_use_aux=None, stardist_prob_thr=None, stardist_nms_thr=None, stardist_window_size_m=None, stardist_window_overlap_m=None, stardist_dedup_iou_thr=None, stardist_cpu=False, stardist_resume=False, stardist_resume_from_labels=False, stardist_skip_sources=None, stardist_skip_sources_file=None, run_sam=True, run_stardist=True, skip_existing_sam=True, log_refinement=False, fast=None, fg_extra=None, crop_smooth_sigma=None, smooth_sigma=None, post_smooth_sigma=None)

Run segmentation; fg_extra=None reuses the bundle count (80 for older bundles).

Source code in samstars/api.py
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
def segment(
    self,
    *,
    out: Path,
    storage: str,
    tiles_dir: Path | None = None,
    img: Path | None = None,
    chm: Path | None = None,
    den: Path | None = None,
    rgb_bands: tuple[int, int, int] | None = None,
    nir_band: int | None = None,
    texture_band: int | None = None,
    device: str = "cpu",
    stardist_input_key: str | None = None,
    stardist_use_aux: bool | None = None,
    stardist_prob_thr: float | None = None,
    stardist_nms_thr: float | None = None,
    stardist_window_size_m: float | None = None,
    stardist_window_overlap_m: float | None = None,
    stardist_dedup_iou_thr: float | None = None,
    stardist_cpu: bool = False,
    stardist_resume: bool = False,
    stardist_resume_from_labels: bool = False,
    stardist_skip_sources: str | None = None,
    stardist_skip_sources_file: Path | None = None,
    run_sam: bool = True,
    run_stardist: bool = True,
    skip_existing_sam: bool = True,
    log_refinement: bool = False,
    fast: bool | None = None,
    fg_extra: int | None = None,
    crop_smooth_sigma: float | None = None,
    smooth_sigma: float | None = None,
    post_smooth_sigma: float | None = None,
) -> SamStarsResult:
    """Run segmentation; fg_extra=None reuses the bundle count (80 for older bundles)."""
    resolved_fg_extra = validate_fg_extra(
        self.defaults.get("fg_extra", DEFAULT_FG_EXTRA) if fg_extra is None else fg_extra
    )
    from samstars.segmentation.engine import run_segmentation

    storage = _normalize_storage(storage)
    out = Path(out)
    if out.resolve() == self.root.resolve():
        raise ValueError("out must be different from the model bundle directory.")
    out.mkdir(parents=True, exist_ok=True)

    resolved_rgb_bands = rgb_bands
    if resolved_rgb_bands is None and self.defaults.get("rgb_bands") is not None:
        resolved_rgb_bands = tuple(self.defaults["rgb_bands"])
    resolved_nir_band = self.defaults.get("nir_band") if nir_band is None else nir_band
    resolved_texture_band = self.defaults.get("texture_band") if texture_band is None else texture_band

    resolved_stardist_input_key = stardist_input_key or self.defaults.get("stardist_input_key", "index")
    resolved_stardist_use_aux = (
        bool(self.defaults.get("stardist_use_aux", True))
        if stardist_use_aux is None
        else stardist_use_aux
    )
    resolved_prob_thr = self.defaults.get("stardist_prob_thr") if stardist_prob_thr is None else stardist_prob_thr
    resolved_nms_thr = self.defaults.get("stardist_nms_thr") if stardist_nms_thr is None else stardist_nms_thr
    resolved_window_size_m = (
        self.defaults.get("stardist_window_size_m")
        if stardist_window_size_m is None
        else stardist_window_size_m
    )
    resolved_window_overlap_m = (
        self.defaults.get("stardist_window_overlap_m", 0.0)
        if stardist_window_overlap_m is None
        else stardist_window_overlap_m
    )
    resolved_dedup_iou_thr = (
        self.defaults.get("stardist_dedup_iou_thr", 0.0)
        if stardist_dedup_iou_thr is None
        else stardist_dedup_iou_thr
    )
    resolved_fast = bool(self.defaults.get("fast", False)) if fast is None else fast
    resolved_crop_sigma = (
        float(self.defaults.get("crop_smooth_sigma", 2.0))
        if crop_smooth_sigma is None
        else crop_smooth_sigma
    )
    resolved_smooth_sigma = (
        float(self.defaults.get("smooth_sigma", 4.0))
        if smooth_sigma is None
        else smooth_sigma
    )
    resolved_post_sigma = (
        float(self.defaults.get("post_smooth_sigma", 0.0))
        if post_smooth_sigma is None
        else post_smooth_sigma
    )

    with self._work_root(out, storage, prefix="samstars-segment-") as work_root:
        with tempfile.TemporaryDirectory(prefix="samstars-stardist-") as model_stage:
            staged_stardist = self._stage_stardist_model(Path(model_stage))
            run_info = run_segmentation(
                tiles_dir=tiles_dir,
                img=img,
                chm=chm,
                den=den,
                rgb_bands=resolved_rgb_bands,
                nir_band=resolved_nir_band,
                texture_band=resolved_texture_band,
                out_dir=work_root,
                sam_ckpt=self.decoder_path,
                device=device,
                stardist_model=staged_stardist,
                stardist_input_key=resolved_stardist_input_key,
                stardist_use_aux=resolved_stardist_use_aux,
                stardist_prob_thr=resolved_prob_thr,
                stardist_nms_thr=resolved_nms_thr,
                stardist_window_size_m=resolved_window_size_m,
                stardist_window_overlap_m=float(resolved_window_overlap_m or 0.0),
                stardist_dedup_iou_thr=float(resolved_dedup_iou_thr or 0.0),
                stardist_cpu=stardist_cpu,
                stardist_resume=stardist_resume,
                stardist_resume_from_labels=stardist_resume_from_labels,
                stardist_skip_sources=stardist_skip_sources,
                stardist_skip_sources_file=stardist_skip_sources_file,
                run_sam=run_sam,
                run_stardist=run_stardist,
                skip_existing_sam=skip_existing_sam,
                log_refinement=log_refinement,
                fast=resolved_fast,
                fg_extra=resolved_fg_extra,
                crop_smooth_sigma=resolved_crop_sigma,
                smooth_sigma=resolved_smooth_sigma,
                post_smooth_sigma=resolved_post_sigma,
            )

        if storage == "temp":
            self._finalize_temp_outputs(temp_root=work_root, out=out)
            work_dir = None
        else:
            work_dir = work_root

    self._write_run_manifest(
        out=out,
        storage=storage,
        model=self,
        work_dir=work_dir,
    )
    labels_dir = out / "labels" if (out / "labels").exists() else None
    return SamStarsResult(
        out=out,
        crowns=out / "crowns" / "crowns.gpkg",
        labels_dir=labels_dir,
        storage=storage,
        work_dir=work_dir,
    )

train(*, tiles_dir=None, img=None, chm=None, den=None, crowns=None, sam_base_ckpt, out, storage, rgb_bands=None, nir_band=None, texture_band=None, device='cpu', chip_size=512, chip_stride=384, sam_epochs=15, sam_min_iters=0, sam_lr=5e-05, fg_extra=DEFAULT_FG_EXTRA, stardist_epochs=50, stardist_min_iters=0, val_fraction=0.2, crop_smooth_sigma=2.0, smooth_sigma=4.0, post_smooth_sigma=0.0, thin_seeds=True, thin_dist=0.8, seed_d_min=4.5, seed_min_dist_px=4, seed_gauss_sigma=2, seed_min_samples=1, seed_merge_radius=3.0, seed_min_canopy_height=2.0, stardist_input_key='index', stardist_use_aux=True, stardist_normalize_inputs=True, stardist_augment=True, stardist_window_size_m=None, stardist_window_overlap_m=0.0, stardist_dedup_iou_thr=0.0, stardist_cpu=False, fast=False) classmethod

Train a model bundle; fg_extra controls extra foreground prompts (0 = seed only).

Source code in samstars/api.py
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
@classmethod
def train(
    cls,
    *,
    tiles_dir: Path | None = None,
    img: Path | None = None,
    chm: Path | None = None,
    den: Path | None = None,
    crowns: Path | None = None,
    sam_base_ckpt: Path,
    out: Path,
    storage: str,
    rgb_bands: tuple[int, int, int] | None = None,
    nir_band: int | None = None,
    texture_band: int | None = None,
    device: str = "cpu",
    chip_size: int = 512,
    chip_stride: int = 384,
    sam_epochs: int = 15,
    sam_min_iters: int = 0,
    sam_lr: float = 5e-5,
    fg_extra: int = DEFAULT_FG_EXTRA,
    stardist_epochs: int = 50,
    stardist_min_iters: int = 0,
    val_fraction: float = 0.2,
    crop_smooth_sigma: float = 2.0,
    smooth_sigma: float = 4.0,
    post_smooth_sigma: float = 0.0,
    thin_seeds: bool = True,
    thin_dist: float = 0.8,
    seed_d_min: float = 4.5,
    seed_min_dist_px: int = 4,
    seed_gauss_sigma: int = 2,
    seed_min_samples: int = 1,
    seed_merge_radius: float = 3.0,
    seed_min_canopy_height: float = 2.0,
    stardist_input_key: str = "index",
    stardist_use_aux: bool = True,
    stardist_normalize_inputs: bool = True,
    stardist_augment: bool = True,
    stardist_window_size_m: float | None = None,
    stardist_window_overlap_m: float = 0.0,
    stardist_dedup_iou_thr: float = 0.0,
    stardist_cpu: bool = False,
    fast: bool = False,
) -> SamStars:
    """Train a model bundle; fg_extra controls extra foreground prompts (0 = seed only)."""
    fg_extra = validate_fg_extra(fg_extra)
    from samstars.data import build_scale_stats_from_proposal_records
    from samstars.segmentation.engine import run_segmentation
    from samstars.training.chips import build_training_chips
    from samstars.training.records import build_stardist_training_records
    from samstars.training.sam_training import train_decoder

    storage = _normalize_storage(storage)
    out = Path(out)
    out.mkdir(parents=True, exist_ok=True)
    for stale in (
        out / "decoder.pth",
        out / "config.json",
        out / "weights.h5",
        out / "thresholds.json",
        out / _BUNDLE_MANIFEST,
    ):
        if stale.exists():
            stale.unlink()

    with cls._work_root(out, storage, prefix="samstars-train-") as work_root:
        training_root = work_root / "_training" if storage == "persistent" else work_root
        prep_root = training_root / "prep"
        training_chips_dir = training_root / "training_chips"
        training_run_dir = training_root / "training_run"
        records_dir = training_root / "stardist_training_records"
        scale_stats = training_root / "training_scale_stats.json"
        stardist_train_root = training_root / "_stardist_model"

        decoder_path = out / "decoder.pth"
        training_tiles_dir = _resolve_training_tiles(
            tiles_dir=tiles_dir,
            img=img,
            chm=chm,
            den=den,
            crowns=crowns,
            rgb_bands=rgb_bands,
            nir_band=nir_band,
            texture_band=texture_band,
            prep_root=prep_root,
            thin_seeds=thin_seeds,
            thin_dist=thin_dist,
            seed_d_min=seed_d_min,
            seed_min_dist_px=seed_min_dist_px,
            seed_gauss_sigma=seed_gauss_sigma,
            seed_min_samples=seed_min_samples,
            seed_merge_radius=seed_merge_radius,
            seed_min_canopy_height=seed_min_canopy_height,
        )

        build_training_chips(
            tiles_dir=training_tiles_dir,
            out_dir=training_chips_dir,
            chip_size=chip_size,
            stride=chip_stride,
        )

        train_decoder(
            chip_dir=training_chips_dir,
            ckpt=Path(sam_base_ckpt),
            out_path=decoder_path,
            epochs=sam_epochs,
            min_iters=sam_min_iters,
            lr=sam_lr,
            device=device,
            fg_extra=fg_extra,
        )

        proposal_result = run_segmentation(
            tiles_dir=training_tiles_dir,
            out_dir=training_run_dir,
            sam_ckpt=decoder_path,
            device=device,
            run_sam=True,
            run_stardist=False,
            fast=fast,
            fg_extra=fg_extra,
            crop_smooth_sigma=crop_smooth_sigma,
            smooth_sigma=smooth_sigma,
            post_smooth_sigma=post_smooth_sigma,
        )

        train_records, val_records = build_stardist_training_records(
            proposal_records=proposal_result["proposal_records"],
            tiles_dir=training_tiles_dir,
            out_dir=records_dir,
            val_fraction=val_fraction,
        )

        build_scale_stats_from_proposal_records(
            proposal_records=proposal_result["proposal_records"],
            out=scale_stats,
            percentiles=(2.0, 98.0),
            chm_key="chm",
            nodata_values=(-9999.0,),
        )

        if stardist_cpu:
            cmd = [
                sys.executable,
                str(Path(__file__).resolve().parent / "training" / "stardist_training.py"),
                "--train-records",
                str(train_records),
                "--val-records",
                str(val_records),
                "--out-dir",
                str(stardist_train_root),
                "--model-name",
                "stardist",
                "--epochs",
                str(stardist_epochs),
                "--min-iters",
                str(stardist_min_iters),
                "--input-key",
                stardist_input_key,
            ]
            if stardist_use_aux:
                cmd.extend(["--use-aux", "--scale-stats", str(scale_stats)])
            if not stardist_normalize_inputs:
                cmd.append("--no-normalize")
            if not stardist_augment:
                cmd.append("--no-augment")
            env = dict(os.environ)
            env["CUDA_VISIBLE_DEVICES"] = ""
            subprocess.run(cmd, check=True, env=env)
        else:
            from samstars.training.stardist_training import train_stardist_model

            train_stardist_model(
                train_records=train_records,
                val_records=val_records,
                out_dir=stardist_train_root,
                model_name="stardist",
                epochs=stardist_epochs,
                min_iters=stardist_min_iters,
                input_key=stardist_input_key,
                use_aux=stardist_use_aux,
                scale_stats_path=scale_stats if stardist_use_aux else None,
                normalize_inputs=stardist_normalize_inputs,
                augment=stardist_augment,
            )

        stardist_dir = stardist_train_root / "stardist"
        shutil.copy2(stardist_dir / "config.json", out / "config.json")
        weight_path = _find_stardist_weight(stardist_dir)
        shutil.copy2(weight_path, out / "weights.h5")
        if (stardist_dir / "thresholds.json").exists():
            shutil.copy2(stardist_dir / "thresholds.json", out / "thresholds.json")
        elif (out / "thresholds.json").exists():
            (out / "thresholds.json").unlink()

    prob_thr, nms_thr = cls._load_stardist_thresholds_from_dir(out)
    cls._write_bundle_manifest(
        out=out,
        defaults={
            "rgb_bands": list(rgb_bands) if rgb_bands is not None else [1, 2, 3],
            "nir_band": nir_band,
            "texture_band": texture_band,
            "stardist_input_key": stardist_input_key,
            "stardist_use_aux": stardist_use_aux,
            "stardist_prob_thr": prob_thr,
            "stardist_nms_thr": nms_thr,
            "stardist_window_size_m": stardist_window_size_m,
            "stardist_window_overlap_m": stardist_window_overlap_m,
            "stardist_dedup_iou_thr": stardist_dedup_iou_thr,
            "stardist_cpu": stardist_cpu,
            "crop_smooth_sigma": crop_smooth_sigma,
            "smooth_sigma": smooth_sigma,
            "post_smooth_sigma": post_smooth_sigma,
            "fast": fast,
            "fg_extra": fg_extra,
        },
    )
    return cls(out)

SamStarsResult dataclass

Paths returned by a segmentation run.

Attributes:

Name Type Description
out Path

Final output directory.

crowns Path

Crown GeoPackage path, produced when refinement runs.

labels_dir Path | None

Label-raster directory when exposed by the run, otherwise None.

storage str

Intermediate storage policy: persistent or temp.

work_dir Path | None

Retained working directory for persistent runs, otherwise None.

Source code in samstars/api.py
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
@dataclass(slots=True)
class SamStarsResult:
    """Paths returned by a segmentation run.

    Attributes:
        out: Final output directory.
        crowns: Crown GeoPackage path, produced when refinement runs.
        labels_dir: Label-raster directory when exposed by the run, otherwise None.
        storage: Intermediate storage policy: persistent or temp.
        work_dir: Retained working directory for persistent runs, otherwise None.
    """

    out: Path
    crowns: Path
    labels_dir: Path | None
    storage: str
    work_dir: Path | None = None

    def to_dict(self) -> dict[str, str | None]:
        """Return a JSON-serializable summary."""
        return {
            "out": str(self.out),
            "crowns": str(self.crowns),
            "labels_dir": str(self.labels_dir) if self.labels_dir is not None else None,
            "storage": self.storage,
            "work_dir": str(self.work_dir) if self.work_dir is not None else None,
        }

to_dict()

Return a JSON-serializable summary.

Source code in samstars/api.py
206
207
208
209
210
211
212
213
214
def to_dict(self) -> dict[str, str | None]:
    """Return a JSON-serializable summary."""
    return {
        "out": str(self.out),
        "crowns": str(self.crowns),
        "labels_dir": str(self.labels_dir) if self.labels_dir is not None else None,
        "storage": self.storage,
        "work_dir": str(self.work_dir) if self.work_dir is not None else None,
    }

segment(*, model, out, storage, tiles_dir=None, img=None, chm=None, den=None, rgb_bands=None, nir_band=None, texture_band=None, device='cpu', stardist_input_key=None, stardist_use_aux=None, stardist_prob_thr=None, stardist_nms_thr=None, stardist_window_size_m=None, stardist_window_overlap_m=None, stardist_dedup_iou_thr=None, stardist_cpu=False, stardist_resume=False, stardist_resume_from_labels=False, stardist_skip_sources=None, stardist_skip_sources_file=None, run_sam=True, run_stardist=True, skip_existing_sam=True, log_refinement=False, fast=None, fg_extra=None, crop_smooth_sigma=None, smooth_sigma=None, post_smooth_sigma=None)

Segment source rasters or prepared tiles using a trained model bundle.

Parameters:

Name Type Description Default
model Path | SamStars

Model bundle path or a loaded SamStars instance.

required
out Path

Segmentation output directory, separate from the model bundle.

required
storage str

persistent keeps intermediates and checkpoints; temp retains final crown outputs after deleting temporary intermediates.

required
tiles_dir Path | None

Prepared tile directories. Supply this instead of img/chm/den.

None
img Path | None

Source imagery. Channel content must match the model's training data.

None
chm Path | None

Canopy heights in meters, aligned to the imagery during preparation.

None
den Path | None

First-return counts or density, consistent with training units.

None
rgb_bands tuple[int, int, int] | None

One-based red, green, blue source indices. None reuses the bundle setting, or (1, 2, 3) when no setting was stored.

None
nir_band int | None

Optional NIR source index. None reuses the bundle setting.

None
texture_band int | None

Optional texture source index. None reuses the bundle setting.

None
device str

PyTorch device for proposals: cpu, cuda, or mps.

'cpu'
stardist_input_key str | None

Override the refinement input key stored in the bundle.

None
stardist_use_aux bool | None

Override use of the normalized CHM refinement channel.

None
stardist_prob_thr float | None

Refinement probability threshold; set with stardist_nms_thr.

None
stardist_nms_thr float | None

Refinement suppression threshold; set with stardist_prob_thr.

None
stardist_window_size_m float | None

Internal refinement window size in projected map units.

None
stardist_window_overlap_m float | None

Window overlap in the same map units.

None
stardist_dedup_iou_thr float | None

Final cross-source polygon deduplication threshold. Zero disables it; positive values below one retain the higher-score polygon when pairwise intersection-over-union reaches the threshold.

None
stardist_cpu bool

Run refinement in a subprocess with CUDA hidden.

False
stardist_resume bool

Reuse complete refinement checkpoints in a persistent run.

False
stardist_resume_from_labels bool

Rebuild checkpoints from labels; also requires stardist_resume. Recovered polygons have no confidence score.

False
stardist_skip_sources str | None

Comma-separated proposal source names to skip.

None
stardist_skip_sources_file Path | None

Text file with one source name per line.

None
run_sam bool

Run proposal generation. False reuses saved proposal records.

True
run_stardist bool

Run refinement. False stops after proposal generation.

True
skip_existing_sam bool

Skip complete proposal outputs already present under out.

True
log_refinement bool

Show detailed refinement logs.

False
fast bool | None

Override the bundle's batched proposal-decoding setting.

None
fg_extra int | None

Override the maximum additional foreground points per seed. None reuses the bundle setting, or 80 for older bundles. Zero keeps only the seed as foreground. Negative points and boxes are unchanged.

None
crop_smooth_sigma float | None

Override per-crop proposal smoothing, in pixels.

None
smooth_sigma float | None

Override proposal mosaic smoothing, in pixels.

None
post_smooth_sigma float | None

Override smoothing after canopy-index fusion, in pixels.

None

Returns:

Type Description
SamStarsResult

Output paths in a SamStarsResult. Final crowns are written to

SamStarsResult

out/crowns/crowns.gpkg when refinement runs. Overlapping tiles can leave

SamStarsResult

overlapping polygons; deduplication does not guarantee disjoint crowns.

Resume only with the same inputs, model, and settings. Use a new output directory when changing them. Band overrides apply to source preparation; prepared tile channels are used as supplied.

Source code in samstars/api.py
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
def segment(
    *,
    model: Path | SamStars,
    out: Path,
    storage: str,
    tiles_dir: Path | None = None,
    img: Path | None = None,
    chm: Path | None = None,
    den: Path | None = None,
    rgb_bands: tuple[int, int, int] | None = None,
    nir_band: int | None = None,
    texture_band: int | None = None,
    device: str = "cpu",
    stardist_input_key: str | None = None,
    stardist_use_aux: bool | None = None,
    stardist_prob_thr: float | None = None,
    stardist_nms_thr: float | None = None,
    stardist_window_size_m: float | None = None,
    stardist_window_overlap_m: float | None = None,
    stardist_dedup_iou_thr: float | None = None,
    stardist_cpu: bool = False,
    stardist_resume: bool = False,
    stardist_resume_from_labels: bool = False,
    stardist_skip_sources: str | None = None,
    stardist_skip_sources_file: Path | None = None,
    run_sam: bool = True,
    run_stardist: bool = True,
    skip_existing_sam: bool = True,
    log_refinement: bool = False,
    fast: bool | None = None,
    fg_extra: int | None = None,
    crop_smooth_sigma: float | None = None,
    smooth_sigma: float | None = None,
    post_smooth_sigma: float | None = None,
) -> SamStarsResult:
    """Segment source rasters or prepared tiles using a trained model bundle.

    Args:
        model: Model bundle path or a loaded SamStars instance.
        out: Segmentation output directory, separate from the model bundle.
        storage: persistent keeps intermediates and checkpoints; temp retains
            final crown outputs after deleting temporary intermediates.
        tiles_dir: Prepared tile directories. Supply this instead of img/chm/den.
        img: Source imagery. Channel content must match the model's training data.
        chm: Canopy heights in meters, aligned to the imagery during preparation.
        den: First-return counts or density, consistent with training units.
        rgb_bands: One-based red, green, blue source indices. None reuses the bundle
            setting, or (1, 2, 3) when no setting was stored.
        nir_band: Optional NIR source index. None reuses the bundle setting.
        texture_band: Optional texture source index. None reuses the bundle setting.
        device: PyTorch device for proposals: cpu, cuda, or mps.
        stardist_input_key: Override the refinement input key stored in the bundle.
        stardist_use_aux: Override use of the normalized CHM refinement channel.
        stardist_prob_thr: Refinement probability threshold; set with stardist_nms_thr.
        stardist_nms_thr: Refinement suppression threshold; set with stardist_prob_thr.
        stardist_window_size_m: Internal refinement window size in projected map units.
        stardist_window_overlap_m: Window overlap in the same map units.
        stardist_dedup_iou_thr: Final cross-source polygon deduplication threshold.
            Zero disables it; positive values below one retain the higher-score
            polygon when pairwise intersection-over-union reaches the threshold.
        stardist_cpu: Run refinement in a subprocess with CUDA hidden.
        stardist_resume: Reuse complete refinement checkpoints in a persistent run.
        stardist_resume_from_labels: Rebuild checkpoints from labels; also requires
            stardist_resume. Recovered polygons have no confidence score.
        stardist_skip_sources: Comma-separated proposal source names to skip.
        stardist_skip_sources_file: Text file with one source name per line.
        run_sam: Run proposal generation. False reuses saved proposal records.
        run_stardist: Run refinement. False stops after proposal generation.
        skip_existing_sam: Skip complete proposal outputs already present under out.
        log_refinement: Show detailed refinement logs.
        fast: Override the bundle's batched proposal-decoding setting.
        fg_extra: Override the maximum additional foreground points per seed.
            None reuses the bundle setting, or 80 for older bundles. Zero keeps
            only the seed as foreground. Negative points and boxes are unchanged.
        crop_smooth_sigma: Override per-crop proposal smoothing, in pixels.
        smooth_sigma: Override proposal mosaic smoothing, in pixels.
        post_smooth_sigma: Override smoothing after canopy-index fusion, in pixels.

    Returns:
        Output paths in a SamStarsResult. Final crowns are written to
        out/crowns/crowns.gpkg when refinement runs. Overlapping tiles can leave
        overlapping polygons; deduplication does not guarantee disjoint crowns.

    Resume only with the same inputs, model, and settings. Use a new output
    directory when changing them. Band overrides apply to source preparation;
    prepared tile channels are used as supplied.
    """
    runtime = SamStars.load(model)
    return runtime.segment(
        out=out,
        storage=storage,
        tiles_dir=tiles_dir,
        img=img,
        chm=chm,
        den=den,
        rgb_bands=rgb_bands,
        nir_band=nir_band,
        texture_band=texture_band,
        device=device,
        stardist_input_key=stardist_input_key,
        stardist_use_aux=stardist_use_aux,
        stardist_prob_thr=stardist_prob_thr,
        stardist_nms_thr=stardist_nms_thr,
        stardist_window_size_m=stardist_window_size_m,
        stardist_window_overlap_m=stardist_window_overlap_m,
        stardist_dedup_iou_thr=stardist_dedup_iou_thr,
        stardist_cpu=stardist_cpu,
        stardist_resume=stardist_resume,
        stardist_resume_from_labels=stardist_resume_from_labels,
        stardist_skip_sources=stardist_skip_sources,
        stardist_skip_sources_file=stardist_skip_sources_file,
        run_sam=run_sam,
        run_stardist=run_stardist,
        skip_existing_sam=skip_existing_sam,
        log_refinement=log_refinement,
        fast=fast,
        fg_extra=fg_extra,
        crop_smooth_sigma=crop_smooth_sigma,
        smooth_sigma=smooth_sigma,
        post_smooth_sigma=post_smooth_sigma,
    )

train(*, tiles_dir=None, img=None, chm=None, den=None, crowns=None, sam_base_ckpt, out, storage, rgb_bands=None, nir_band=None, texture_band=None, device='cpu', chip_size=512, chip_stride=384, sam_epochs=15, sam_min_iters=0, sam_lr=5e-05, fg_extra=DEFAULT_FG_EXTRA, stardist_epochs=50, stardist_min_iters=0, val_fraction=0.2, crop_smooth_sigma=2.0, smooth_sigma=4.0, post_smooth_sigma=0.0, thin_seeds=True, thin_dist=0.8, seed_d_min=4.5, seed_min_dist_px=4, seed_gauss_sigma=2, seed_min_samples=1, seed_merge_radius=3.0, seed_min_canopy_height=2.0, stardist_input_key='index', stardist_use_aux=True, stardist_normalize_inputs=True, stardist_augment=True, stardist_window_size_m=None, stardist_window_overlap_m=0.0, stardist_dedup_iou_thr=0.0, stardist_cpu=False, fast=False)

Train a model bundle from a labeled scene or labeled tile directories.

Parameters:

Name Type Description Default
tiles_dir Path | None

Directory of consistently raw or prepared labeled tiles. Supply this instead of the four scene inputs.

None
img Path | None

RGB or multiband source imagery with a projected CRS and square pixels.

None
chm Path | None

Canopy height raster in meters; aligned to img during preparation.

None
den Path | None

First-return count or density raster; aligned to img during preparation.

None
crowns Path | None

Crown GeoPackage with one polygon feature per tree.

None
sam_base_ckpt Path

Base ViT-L checkpoint used to initialize proposal training.

required
out Path

Destination model bundle directory. Use a new path for each experiment.

required
storage str

persistent retains intermediates under out/_training; temp retains only the finished bundle.

required
rgb_bands tuple[int, int, int] | None

One-based source indices in red, green, blue order. Defaults to (1, 2, 3), without inferring a sensor from the band count.

None
nir_band int | None

Optional source NIR index for the NDVI cost term. Omit for RGB.

None
texture_band int | None

Optional source texture index; otherwise use mean RGB intensity.

None
device str

PyTorch device for proposal training: cpu, cuda, or mps.

'cpu'
chip_size int

Training chip width and height in pixels.

512
chip_stride int

Spacing between training chips in pixels.

384
sam_epochs int

Number of proposal-decoder training epochs.

15
sam_min_iters int

Minimum proposal training iterations; may increase epochs.

0
sam_lr float

Proposal-decoder learning rate.

5e-05
fg_extra int

Maximum additional foreground points per seed, a nonnegative integer. Zero keeps only the seed as foreground; the default is 80. Used for decoder training and the proposals that train refinement, and stored in the bundle for later segmentation.

DEFAULT_FG_EXTRA
stardist_epochs int

Number of refinement training epochs.

50
stardist_min_iters int

Minimum refinement training iterations.

0
val_fraction float

Fraction of refinement records assigned to validation. This is a record split, not a spatial holdout.

0.2
crop_smooth_sigma float

Proposal smoothing scale within each crop, in pixels.

2.0
smooth_sigma float

Proposal mosaic smoothing scale, in pixels.

4.0
post_smooth_sigma float

Optional smoothing after canopy-index fusion, in pixels.

0.0
thin_seeds bool

Thin nearby seed points after detection.

True
thin_dist float

Seed thinning distance in projected CRS units.

0.8
seed_d_min float

Minimum peak value, applied to both CHM and density.

4.5
seed_min_dist_px int

Seed peak-search radius in pixels.

4
seed_gauss_sigma int

Seed detection smoothing scale in pixels.

2
seed_min_samples int

Minimum samples in a seed cluster.

1
seed_merge_radius float

Candidate grouping distance in projected CRS units.

3.0
seed_min_canopy_height float

Minimum canopy height at a seed, in meters.

2.0
stardist_input_key str

Refinement input record key, usually index.

'index'
stardist_use_aux bool

Include normalized CHM as an auxiliary refinement channel.

True
stardist_normalize_inputs bool

Normalize refinement inputs per channel.

True
stardist_augment bool

Apply training augmentation to refinement samples.

True
stardist_window_size_m float | None

Default refinement window size for later segmentation, in map units, normally meters; None processes each proposal raster whole.

None
stardist_window_overlap_m float

Overlap between refinement windows in map units.

0.0
stardist_dedup_iou_thr float

Default final polygon deduplication threshold; zero disables it, positive values below one suppress matching overlaps.

0.0
stardist_cpu bool

Run refinement training in a subprocess with CUDA hidden.

False
fast bool

Use batched proposal decoding.

False

Returns:

Type Description
SamStars

A SamStars instance backed by the saved bundle. Band settings and

SamStars

segmentation defaults are recorded in manifest.json. Prepared tiles

SamStars

retain their existing channel order and cost rasters.

Source code in samstars/api.py
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
def train(
    *,
    tiles_dir: Path | None = None,
    img: Path | None = None,
    chm: Path | None = None,
    den: Path | None = None,
    crowns: Path | None = None,
    sam_base_ckpt: Path,
    out: Path,
    storage: str,
    rgb_bands: tuple[int, int, int] | None = None,
    nir_band: int | None = None,
    texture_band: int | None = None,
    device: str = "cpu",
    chip_size: int = 512,
    chip_stride: int = 384,
    sam_epochs: int = 15,
    sam_min_iters: int = 0,
    sam_lr: float = 5e-5,
    fg_extra: int = DEFAULT_FG_EXTRA,
    stardist_epochs: int = 50,
    stardist_min_iters: int = 0,
    val_fraction: float = 0.2,
    crop_smooth_sigma: float = 2.0,
    smooth_sigma: float = 4.0,
    post_smooth_sigma: float = 0.0,
    thin_seeds: bool = True,
    thin_dist: float = 0.8,
    seed_d_min: float = 4.5,
    seed_min_dist_px: int = 4,
    seed_gauss_sigma: int = 2,
    seed_min_samples: int = 1,
    seed_merge_radius: float = 3.0,
    seed_min_canopy_height: float = 2.0,
    stardist_input_key: str = "index",
    stardist_use_aux: bool = True,
    stardist_normalize_inputs: bool = True,
    stardist_augment: bool = True,
    stardist_window_size_m: float | None = None,
    stardist_window_overlap_m: float = 0.0,
    stardist_dedup_iou_thr: float = 0.0,
    stardist_cpu: bool = False,
    fast: bool = False,
) -> SamStars:
    """Train a model bundle from a labeled scene or labeled tile directories.

    Args:
        tiles_dir: Directory of consistently raw or prepared labeled tiles.
            Supply this instead of the four scene inputs.
        img: RGB or multiband source imagery with a projected CRS and square pixels.
        chm: Canopy height raster in meters; aligned to img during preparation.
        den: First-return count or density raster; aligned to img during preparation.
        crowns: Crown GeoPackage with one polygon feature per tree.
        sam_base_ckpt: Base ViT-L checkpoint used to initialize proposal training.
        out: Destination model bundle directory. Use a new path for each experiment.
        storage: persistent retains intermediates under out/_training; temp
            retains only the finished bundle.
        rgb_bands: One-based source indices in red, green, blue order. Defaults
            to (1, 2, 3), without inferring a sensor from the band count.
        nir_band: Optional source NIR index for the NDVI cost term. Omit for RGB.
        texture_band: Optional source texture index; otherwise use mean RGB intensity.
        device: PyTorch device for proposal training: cpu, cuda, or mps.
        chip_size: Training chip width and height in pixels.
        chip_stride: Spacing between training chips in pixels.
        sam_epochs: Number of proposal-decoder training epochs.
        sam_min_iters: Minimum proposal training iterations; may increase epochs.
        sam_lr: Proposal-decoder learning rate.
        fg_extra: Maximum additional foreground points per seed, a nonnegative
            integer. Zero keeps only the seed as foreground; the default is 80.
            Used for decoder training and the proposals that train refinement,
            and stored in the bundle for later segmentation.
        stardist_epochs: Number of refinement training epochs.
        stardist_min_iters: Minimum refinement training iterations.
        val_fraction: Fraction of refinement records assigned to validation.
            This is a record split, not a spatial holdout.
        crop_smooth_sigma: Proposal smoothing scale within each crop, in pixels.
        smooth_sigma: Proposal mosaic smoothing scale, in pixels.
        post_smooth_sigma: Optional smoothing after canopy-index fusion, in pixels.
        thin_seeds: Thin nearby seed points after detection.
        thin_dist: Seed thinning distance in projected CRS units.
        seed_d_min: Minimum peak value, applied to both CHM and density.
        seed_min_dist_px: Seed peak-search radius in pixels.
        seed_gauss_sigma: Seed detection smoothing scale in pixels.
        seed_min_samples: Minimum samples in a seed cluster.
        seed_merge_radius: Candidate grouping distance in projected CRS units.
        seed_min_canopy_height: Minimum canopy height at a seed, in meters.
        stardist_input_key: Refinement input record key, usually index.
        stardist_use_aux: Include normalized CHM as an auxiliary refinement channel.
        stardist_normalize_inputs: Normalize refinement inputs per channel.
        stardist_augment: Apply training augmentation to refinement samples.
        stardist_window_size_m: Default refinement window size for later segmentation,
            in map units, normally meters; None processes each proposal raster whole.
        stardist_window_overlap_m: Overlap between refinement windows in map units.
        stardist_dedup_iou_thr: Default final polygon deduplication threshold;
            zero disables it, positive values below one suppress matching overlaps.
        stardist_cpu: Run refinement training in a subprocess with CUDA hidden.
        fast: Use batched proposal decoding.

    Returns:
        A SamStars instance backed by the saved bundle. Band settings and
        segmentation defaults are recorded in manifest.json. Prepared tiles
        retain their existing channel order and cost rasters.
    """
    return SamStars.train(
        tiles_dir=tiles_dir,
        img=img,
        chm=chm,
        den=den,
        crowns=crowns,
        sam_base_ckpt=sam_base_ckpt,
        out=out,
        storage=storage,
        rgb_bands=rgb_bands,
        nir_band=nir_band,
        texture_band=texture_band,
        device=device,
        chip_size=chip_size,
        chip_stride=chip_stride,
        sam_epochs=sam_epochs,
        sam_min_iters=sam_min_iters,
        sam_lr=sam_lr,
        fg_extra=fg_extra,
        stardist_epochs=stardist_epochs,
        stardist_min_iters=stardist_min_iters,
        val_fraction=val_fraction,
        crop_smooth_sigma=crop_smooth_sigma,
        smooth_sigma=smooth_sigma,
        post_smooth_sigma=post_smooth_sigma,
        thin_seeds=thin_seeds,
        thin_dist=thin_dist,
        seed_d_min=seed_d_min,
        seed_min_dist_px=seed_min_dist_px,
        seed_gauss_sigma=seed_gauss_sigma,
        seed_min_samples=seed_min_samples,
        seed_merge_radius=seed_merge_radius,
        seed_min_canopy_height=seed_min_canopy_height,
        stardist_input_key=stardist_input_key,
        stardist_use_aux=stardist_use_aux,
        stardist_normalize_inputs=stardist_normalize_inputs,
        stardist_augment=stardist_augment,
        stardist_window_size_m=stardist_window_size_m,
        stardist_window_overlap_m=stardist_window_overlap_m,
        stardist_dedup_iou_thr=stardist_dedup_iou_thr,
        stardist_cpu=stardist_cpu,
        fast=fast,
    )