> ## Documentation Index
> Fetch the complete documentation index at: https://docs.wherobots.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Detecting field boundaries with RasterFlow

Public Preview

> [!TIP]
>
> The following content is a read-only preview of an executable Jupyter notebook.
>
> To run this notebook interactively:
>
> 1. Go to [**Models**](https://cloud.wherobots.com/models) in Wherobots Cloud.
> 2. Select the model whose notebook you wish to run.
> 3. Click **Try it**, select the **Solution notebook** tab, then click **Open the solution notebook**.

![ftw banner](https://mintcdn.com/wherobots/XTZef6cJhZI1PP0b/tutorials/example-notebooks/images/rasterflow-ftw-ftw-banner.jpg?fit=max\&auto=format\&n=XTZef6cJhZI1PP0b\&q=85\&s=7e72f75b81b9f9075d41a22bdef0f416)

This notebook will guide you through detecting field boundaries from satellite imagery, using Wherobots RasterFlow and the [Fields of the World (FTW)](https://fieldsofthe.world/)<sup>1</sup> model. You will gain a hands-on understanding of how to run models like Fields of the World on your selected area of interest, vectorize the model outputs, and work with those vectors in WherobotsDB.

### Fields of the World (FTW)

The [Fields of the World (FTW)](https://fieldsofthe.world/) model is an example of an open source segmentation model that can predict crop field boundaries.

This model predicts 3 classes:

* non\_field\_background
* field
* field\_boundaries

It was trained on [Sentinel-2](https://sentinels.copernicus.eu/documents/247904/685211/Sentinel-2_User_Handbook) satellite imagery and labeled crop field data from 24 countries across 4 continents.

## Inference on seasonal planting / harvest multi-spectral imagery

We'll run the Fields of the World model on median pixel mosaics for the planting and harvest seasons using 4 multi-spectral bands for each season: Red, Green, Blue, and NIR. This data is sourced from [Sentinel-2 L2A product](https://sentinels.copernicus.eu/documents/247904/685211/Sentinel-2_User_Handbook)<sup>2</sup> from the European Space Agency.

Rather than needing to create these mosaics manually, we'll use RasterFlow's registered datasets for Sentinel-2 seasonal mosaics, which are built in to this model recipe.

## Preview: model inputs and outputs

The interactive map linked below shows the input imagery and model outputs for this notebook's example AOI. Toggle layers in the sidebar to compare the inputs, the raster model output, and the vectorized geometries side-by-side.

**Layers** (top layer first, as in the map's layer list):

* *FTW PM Tiles*: Field boundary polygons in PMTiles format, with a mean and standard deviation confidence score for each field
* *FTW vector geometries*: Polygons of detected fields, derived from the raster output
* *FTW model outputs*: Raster output from the model, shown using the `field_boundaries` band
* *FTW input harvest mosaic*: RGB Sentinel-2 median-pixel mosaic for the harvest season
* *FTW input planting mosaic*: RGB Sentinel-2 median-pixel mosaic for the planting season

View the interactive map [here](https://viz.wherobots.com/?z=12.41\&lat=37.71223\&lng=-100.95046\&l0.id=5b4405dc-d603-47dc-ae09-e0faf3a6f445\&l0.src=s3%3A%2F%2Fwherobots-examples%2Frasterflow%2Fmosaics%2Fftw_haskell_optimized.zarr\&l0.name=FTW+input+planting+mosaic\&l0.clim=533.6418968402297%2C4109.013308997522\&l0.mode=rgb\&l0.rgb=s2med_planting%3AB04%2Cs2med_planting%3AB03%2Cs2med_planting%3AB02%2Cband\&l0.var=variables\&l1.id=8b1b90e5-7906-4b4e-aa10-57764850aa4f\&l1.src=s3%3A%2F%2Fwherobots-examples%2Frasterflow%2Fmosaics%2Fftw_haskell_optimized.zarr\&l1.name=FTW+input+harvest+mosaic\&l1.clim=297.7345099947093%2C1247.8318047602793\&l1.mode=rgb\&l1.rgb=s2med_harvest%3AB04%2Cs2med_harvest%3AB03%2Cs2med_harvest%3AB02%2Cband\&l1.var=variables\&l2.id=19bfda38-982f-4b27-b61f-982f8f00119a\&l2.src=s3%3A%2F%2Fwherobots-examples%2Frasterflow%2Fmodel-outputs%2Fftw_optimized.zarr\&l2.name=FTW+model+outputs\&l2.vis=0\&l2.clim=0.0002047998614793119%2C0.7692958755736328\&l2.mode=single\&l2.rgb=field_boundaries%2Cfield%2Cfield_boundaries%2Cband\&l2.var=variables\&l2.seli.band=2\&l3.id=aee604ee-f1ea-4fe7-9c7c-1be8b5b2a99e\&l3.src=s3%3A%2F%2Fwherobots-examples%2Frasterflow%2Fvectors%2Fftw_haskell.parquet%2F\&l3.name=FTW+vector+geometries\&l3.type=geoparquet\&l3.vis=0\&l3.fill=%23ef4444\&l3.line=%23dc2626\&l3.lw=2\&l3.cc=%23ef4444\&l3.cr=5\&l4.id=1b4a7680-4f0e-4fb0-9b79-a4472908947b\&l4.src=s3%3A%2F%2Fwherobots-examples%2Frasterflow%2Fmodel-outputs%2Fftw_haskell_field_boundaries.pmtiles\&l4.name=FTW+PM+Tiles\&l4.type=pmtiles\&l4.fill=%233b82f6\&l4.line=%232563eb\&l4.lw=2\&l4.cc=%233b82f6\&l4.cr=5\&title=FTW+Haskell+County+KS).

## Selecting an Area of Interest (AOI)

To start, we will choose an Area of Interest (AOI) for our analysis. The area around Haskell County, Kansas has some interesting crop field patterns so we will try out the model there.

```python theme={"system"}
import os

import shapely
import wkls
from sedona.spark import *

config = SedonaContext.builder().getOrCreate()
sedona = SedonaContext.create(config)

# Generate a WKT geometry for Haskell County, Kansas using Well-Known Locations (https://github.com/wherobots/wkls)
aoi = wkls.us.ks.haskellcounty.wkt()

min_lon, min_lat, max_lon, max_lat = shapely.from_wkt(aoi).bounds
print(f"Bounds: [{min_lon:.4f}, {min_lat:.4f}, {max_lon:.4f}, {max_lat:.4f}]")
```

## Using the Wherobots Tasks API

Each RasterFlow workflow runs as a task through the [Wherobots Python SDK](https://pypi.org/project/wherobots-python-sdk/). `run_task` below starts a task run, waits for it to finish, and returns its output value. Recipes return an object with `input_mosaic` and `result`; standalone tasks return a URI. Call `wb.tasks.get("<task name>").input_schema` to see every input a task accepts.

```python theme={"system"}
import time

from wherobots import TaskRunState, Wherobots

# In a Wherobots notebook the SDK uses your Wherobots credentials, elsewhere it reads WHEROBOTS_API_KEY
wb = Wherobots()


def run_task(task_name, inputs, poll_seconds=30):
    """Run a RasterFlow task, wait for it to finish, and return its output value."""
    run = wb.task_runs.get(wb.tasks.run(task_name, inputs, region="aws-us-west-2").task_run_id)
    print(f"Started {task_name} run {run.task_run_id}")
    while run.is_active:
        time.sleep(poll_seconds)
        run = wb.task_runs.get(run.task_run_id)
    if run.state != TaskRunState.SUCCEEDED:
        raise RuntimeError(f"{task_name} run {run.task_run_id} ended {run.state}: {run.error_message}")
    # A successful run can temporarily have no results if the output read fails.
    for _ in range(3):
        if run.results is not None:
            break
        time.sleep(poll_seconds)
        run = wb.task_runs.get(run.task_run_id)
    if run.results is None:
        raise RuntimeError(
            f"Results for successful run {run.task_run_id} are unavailable. "
            "Fetch this run again with wb.task_runs.get(run_id); do not resubmit the task."
        )
    # The single task output can be a URI or a structured recipe result.
    (output,) = run.results.values()
    return output
```

## Running a model

RasterFlow has pre-defined workflows to simplify orchestration of the processing steps for model inference.  These steps include:

* Ingesting imagery for the specified Area of Interest (AOI)
* Generating a seamless image from multiple image tiles (a mosaic)
* Running inference with the selected model

The recipe returns `input_mosaic` for the source imagery and `result` for the predictions. Each contains a `mosaic_index_uri` for its GeoParquet index and a `first_row_mosaic` for its first Zarr store.

Note: This step will take approximately 30 minutes to complete.

```python theme={"system"}
recipe_output = run_task(
    "predict_mosaic_recipe",
    {
        # Area of Interest as WKT (EPSG:4326)
        "aoi": aoi,

        # Date range for imagery to be used by the model, as RFC 3339 timestamps
        "start": "2023-01-01T00:00:00Z",
        "end": "2024-01-01T00:00:00Z",

        # Coordinate Reference System for the output mosaic
        "target_crs": "EPSG:3857",

        # The model recipe to be used for inference (FTW in this case)
        "model_recipe": "ftw",
    },
)

# The recipe returns both the input imagery and the prediction mosaic.
input_mosaic_index_uri = recipe_output["input_mosaic"]["mosaic_index_uri"]
input_mosaic_store = recipe_output["input_mosaic"]["first_row_mosaic"]
print(f"Input imagery: {input_mosaic_store}")

model_output_index_uri = recipe_output["result"]["mosaic_index_uri"]

# Inspect the prediction index (one row per output mosaic location)
model_output_index_df = sedona.read.format("geoparquet").load(model_output_index_uri)
model_output_index_df.show(truncate=60)
```

```python theme={"system"}
# This example AOI has one geometry, so we select the first (only) mosaic location.
model_output_store = model_output_index_df.first()["location"]

model_output_store
```

## (Optional) Build an optimized Zarr for visualization

RasterFlow writes its outputs as Zarr stores at native resolution. To explore them interactively on [cloud.wherobots.com/map](https://cloud.wherobots.com/map), you can build an *optimized* multiscale Zarr. `build_zarr_multiscales` adds downsampled overview levels (image pyramids) to the store so the map can stream coarse tiles when zoomed out and full-resolution pixels when zoomed in.

This step is optional and can take a few minutes for large outputs, so the code below is commented out by default — uncomment it to run it.

Pass `aoi` to select a chunk-aligned bounding window from a single Zarr source. It accepts polygon or multipolygon WKT in EPSG:4326, or an S3 GeoJSON or GeoParquet URI with a CRS. Pixels outside the polygon remain within that rectangular window. Omit `aoi` to process the full store.

```python theme={"system"}
# optimized_store = run_task("build_zarr_multiscales", {"source_store": model_output_store, "aoi": aoi})
# optimized_store
```

## Visualizing outputs

You can visualize the Zarr, GeoParquet, and other geospatial outputs using [cloud.wherobots.com/map](https://cloud.wherobots.com/map).

## Vectorize the raster model outputs

The output for the FTW model is a raster with three classes as bands: field, field\_boundaries, and non\_field\_background.

We will run a seperate flow to convert the fields and field boundaries into vector geometries.  Converting these results to geometries allows us to more easily post process the results or join the results with other vector data.

```python theme={"system"}
import xarray as xr
import s3fs
import zarr
# Determine the classes that are predicted by the model
fs = s3fs.S3FileSystem(profile="default", asynchronous=True)
zstore = zarr.storage.FsspecStore(fs, path=model_output_store[5:])
ds = xr.open_zarr(zstore)
model_features = ds['band'].data.tolist()

# Remove the 'non_field_background' class for vectorization
vector_features = [f for f in model_features if f != 'non_field_background']    
```

```python theme={"system"}
# Note: this should take about 5 minutes to complete
vectorized_results_uri = run_task(
    "vectorize_mosaic",
    {
        "mosaic_uri": model_output_store,
        "features": vector_features,
        "threshold": 0.5,
        "stats": True,
        "medial_skeletonize": False,
    },
)

print(vectorized_results_uri)
```

## Save the vectorized results to the catalog

We can store these vectorized outputs in the catalog by using WherobotsDB to persist the GeoParquet results.

```python theme={"system"}
sedona.sql("CREATE DATABASE IF NOT EXISTS examples_temp.ftw_db")

vectorize_result_df = sedona.read.format("geoparquet").load(vectorized_results_uri)
vectorize_result_df = vectorize_result_df.withColumnRenamed("label", "layer")
vectorize_result_df.writeTo("examples_temp.ftw_db.ftw_vectorized").createOrReplace()
```

## Visualize the vectorized results

To visualize the vectorized results, we will show the fields around Plymell, Kansas and filter out results with a score lower than 0.5. This threshold was determined through observation to strike a balance: it eliminates obvious noise without being overly aggressive, ensuring that we don't accidentally filter out too many relevant results.

```python theme={"system"}
from sedona.spark.sql.st_constructors import ST_GeomFromText
from sedona.spark.sql.st_predicates import ST_Intersects
import pyspark.sql.functions as f

# Bounding box for Plymell, Kansas
plymell_wkt = "POLYGON ((-100.98 37.83, -100.98 37.68, -100.8 37.68, -100.8 37.83, -100.98 37.83))"
vectorize_result_filtered_df = vectorize_result_df.filter("layer == 'field'").filter("score_mean > 0.5") \
    .filter(ST_Intersects(f.col("geometry"), ST_GeomFromText(lit(plymell_wkt))))
```

We will apply some WherobotsDB vector post processing operations to refine the model results.

```python theme={"system"}
tolerance = 0.00001
decimal_places = 6  # roughly 10cm in lat/lon
df = vectorize_result_filtered_df.withColumn("geometry", f.expr("ST_MakeValid(geometry)"))
df = df.withColumn("geometry", f.expr("ST_SetSRID(geometry, 4326)")) # vectorize_mosaic defaults to returning geometries in the CRS EPSG:4326
df = df.withColumn("geometry", f.expr(f"ST_ReducePrecision(geometry, {decimal_places})"))
df = df.withColumn("geometry", f.expr(f"ST_SimplifyPreserveTopology(geometry, {tolerance})"))
df = df.repartition(200)
df.show()
```

```python theme={"system"}
from wherobots_gl import Map

# Wherobots-GL Map is URL-based, so write the post-processed df to GeoParquet first.
vectorized_viz_path = os.getenv("USER_S3_PATH") + "ftw_vectorized_viz.parquet"
df.write.format("geoparquet").mode("overwrite").save(vectorized_viz_path)

Map(layers=[{"type": "geoparquet", "source": vectorized_viz_path, "name": "Vectorized results"}])
```

## Generate PM Tiles for visualization

To improve visualization performance of a large number of geometries, we can use Wherobots built-in high performance PM tile generator.

The FTW model has a tendency to create extremely large boundary geometries, which doesn't play nicely with PMTiles. To avoid this we subdivide the boundary geometries.

```python theme={"system"}
fields_df = df.where("layer = 'field'")
# 1266 is the vertex count of the second-largest boundary geometry.
# We use this instead of the absolute largest boundary (an extreme outlier)
# so the subdivision threshold is high enough to keep most geometries intact
# while still forcing that outlier-sized boundary to be subdivided for
# better PMTiles rendering performance.
boundaries_df = df.where("layer = 'field_boundaries'").withColumn("geometry", f.expr("ST_SubDivideExplode(geometry, 1266)"))
tile_features_df = fields_df.withColumn("layer", f.lit("fields")).unionByName(
    boundaries_df.withColumn("layer", f.lit("boundaries"))
)
```

```python theme={"system"}
from wherobots import vtiles
full_tiles_path = os.getenv("USER_S3_PATH") + "tiles.pmtiles"
vtiles.generate_pmtiles(tile_features_df, full_tiles_path)
```

```python theme={"system"}
vtiles.show_pmtiles(full_tiles_path)
```

## Viewing the PMTiles on the Wherobots Cloud map

Open the PMTiles archive on [cloud.wherobots.com/map](https://cloud.wherobots.com/map) with the link printed below. The map reads the archive from your storage with your Wherobots credentials, so you don't need a pre-signed URL.

```python theme={"system"}
from urllib.parse import quote

print(f"View on the map: https://cloud.wherobots.com/map?l0.src={quote(full_tiles_path, safe='')}")
```

### References

1. **Kerner, H., Chaudhari, S., Ghosh, A., Robinson, C., Ahmad, A., Choi, E., Jacobs, N., Holmes, C., Mohr, M., et al. (2024).** Fields of The World: A Machine Learning Benchmark Dataset For Global Agricultural Field Boundary Segmentation. *arXiv preprint arXiv:2409.16252*. Accepted at AAAI-2025 Artificial Intelligence for Social Impact (AISI) track.
2. ESA. (2015). Sentinel-2 User Handbook (Issue 1, Rev. 2). European Space Agency. [https://sentinels.copernicus.eu/documents/247904/685211/Sentinel-2\_User\_Handbook](https://sentinels.copernicus.eu/documents/247904/685211/Sentinel-2_User_Handbook)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.