Skip to content

samstars.training.chips

samstars.training.chips

Build proposal-decoder training chips from prepared tiles and crown annotations.

build_training_chips(tiles_dir, out_dir, chip_size=512, stride=None, image_bands=(1, 2, 3), skip_tiles=())

Build proposal-decoder training chips from labeled tiles.

Source code in samstars/training/chips.py
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 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
148
149
150
151
152
153
def build_training_chips(
    tiles_dir: Path,
    out_dir: Path,
    chip_size: int = 512,
    stride: int | None = None,
    image_bands: tuple[int, ...] = (1, 2, 3),
    skip_tiles: tuple[str, ...] = (),
) -> int:
    """Build proposal-decoder training chips from labeled tiles."""
    stride = chip_size if stride is None else int(stride)
    skip_set = set(skip_tiles)

    for subdir in ("images", "masks", "chm", "prompts"):
        (out_dir / subdir).mkdir(parents=True, exist_ok=True)

    written = 0
    for tile in _iter_tiles(tiles_dir, skip_set):
        img_path = tile / "img.tif"
        crowns_path = tile / "crowns.gpkg"
        chm_path = tile / "chm.tif"
        if not img_path.exists() or not crowns_path.exists() or not chm_path.exists():
            print(f"Skipping {tile.name}: missing img.tif, crowns.gpkg, or chm.tif")
            continue

        with rasterio.open(img_path) as src:
            height, width = src.height, src.width
            transform = src.transform
            crs = src.crs
            image = src.read(image_bands).astype(np.float32)

        with rasterio.open(chm_path) as chm_src:
            chm = chm_src.read(1).astype(np.float32)

        crowns = gpd.read_file(crowns_path)
        if crowns.empty:
            print(f"Skipping {tile.name}: empty crowns")
            continue
        if crowns.crs is None:
            crowns = crowns.set_crs(crs)
        elif crowns.crs != crs:
            crowns = crowns.to_crs(crs)

        tile_count = 0
        chip_id = 0
        for y0 in range(0, height, stride):
            for x0 in range(0, width, stride):
                y1 = min(y0 + chip_size, height)
                x1 = min(x0 + chip_size, width)
                if y1 - y0 < 1 or x1 - x0 < 1:
                    continue

                window = rasterio.windows.Window(x0, y0, x1 - x0, y1 - y0)
                win_transform = rasterio.windows.transform(window, transform)
                chip_bounds = box(*rasterio.transform.array_bounds(y1 - y0, x1 - x0, win_transform))
                clipped = _clip_annotations(crowns, chip_bounds)
                if clipped.empty:
                    continue

                image_chip = image[:, y0:y1, x0:x1]
                chm_chip = chm[y0:y1, x0:x1]
                pad_h = chip_size - image_chip.shape[1]
                pad_w = chip_size - image_chip.shape[2]
                if pad_h or pad_w:
                    image_chip = np.pad(image_chip, ((0, 0), (0, pad_h), (0, pad_w)), mode="constant")
                    chm_chip = np.pad(chm_chip, ((0, pad_h), (0, pad_w)), mode="constant")

                base_image_chip = image_chip.astype(np.float32)
                base_chm_chip = chm_chip.astype(np.float32)
                for geom in clipped.geometry:
                    mask_chip = _rasterize_one_geometry(geom, (y1 - y0, x1 - x0), win_transform)
                    if pad_h or pad_w:
                        mask_chip = np.pad(mask_chip, ((0, pad_h), (0, pad_w)), mode="constant")

                    prompt = _prompt_from_mask(mask_chip)
                    if prompt is None:
                        continue

                    stem = f"{tile.name}_{chip_id}"
                    np.save(out_dir / "images" / f"{stem}.npy", base_image_chip)
                    np.save(out_dir / "masks" / f"{stem}.npy", mask_chip.astype(np.uint8))
                    np.save(out_dir / "chm" / f"{stem}.npy", base_chm_chip)
                    _save_prompt_json(out_dir / "prompts" / f"{stem}.json", prompt)

                    chip_id += 1
                    tile_count += 1
                    written += 1

        print(f"{tile.name}: wrote {tile_count} training chips")

    print(f"Built {written} training chips in {out_dir}")
    return written

main()

Run the command-line entry point.

Source code in samstars/training/chips.py
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
def main() -> None:
    """Run the command-line entry point."""
    parser = argparse.ArgumentParser(description="Build proposal-decoder training chips from labeled tiles.")
    parser.add_argument("--tiles-dir", type=Path, required=True, help="Directory containing prepared tile folders")
    parser.add_argument("--out-dir", type=Path, required=True, help="Directory to write training chips")
    parser.add_argument("--chip-size", type=int, default=512, help="Output chip size in pixels")
    parser.add_argument(
        "--stride",
        type=int,
        default=None,
        help="Chip stride in pixels; defaults to the chip size when omitted",
    )
    parser.add_argument(
        "--image-bands",
        type=int,
        nargs="+",
        default=(1, 2, 3),
        help="1-based raster bands to include in each training chip",
    )
    parser.add_argument(
        "--skip-tiles",
        nargs="*",
        default=(),
        help="Tile directory names to skip",
    )
    args = parser.parse_args()

    build_training_chips(
        tiles_dir=args.tiles_dir,
        out_dir=args.out_dir,
        chip_size=args.chip_size,
        stride=args.stride,
        image_bands=tuple(args.image_bands),
        skip_tiles=tuple(args.skip_tiles),
    )