Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Cleaning raw masks, vectorising them and computing object properties

1. Motivation

The previous page produced raw instance predictions. This page cleans them up, converts them to vector polygons, and computes the geometric properties that make the result genuinely useful for downstream analysis, the same finishing sequence from L07’s building workflow, adapted here for instance data specifically.

A raw prediction is rarely the finished product. Small spurious detections, tiny gaps between adjacent fields, and complex pixel-level edges all need addressing before a result is ready to share, join with other data, or analyze statistically. This page is what turns “a model produced some output” into “a usable field-boundary dataset.”


2. Core idea

The finishing sequence has four steps: clean the raw instance mask, convert it to vector polygons, visually compare it against the source imagery, and compute geometric properties for each detected field. Each step depends on the one before it, and skipping the cleaning step in particular tends to show up later as noisy, hard-to-interpret statistics.


3. Workflow

Converting raw neural network predictions into GIS-ready vector data requires post-processing. While raw instance rasters assign unique IDs to detected objects, they often contain small noise artifacts, internal gaps, or boundary irregularities. This workflow covers how to clean instance rasters, convert them into vector geometries, verify spatial alignment, calculate geometric shape attributes, and use geometric properties for spatial QA/QC.


A. Raw prediction recovery

First, we re-establish the dataset environment, select a test image, and generate raw instance predictions:


B. Cleaning instance masks

Raw predictions frequently contain minor false-positive pixels (spurious noise) or internal holes (unconfident pixels inside an otherwise solid object). The clean_instance_mask() function addresses both issues:

Post-processing operates through two spatial parameters:

  1. min_area=100 (Removing Spurious Noise): Connected pixel components smaller than 100 cells are removed.

  1. max_hole_area=100 (Filling Internal Gaps): Internal gaps or unassigned pixels within a detected field up to 100 pixels are filled, producing solid object geometries.


C. Vectorizing the cleaned mask

Once the instance raster is cleaned, raster_to_vector() converts each distinct object ID into an individual vector polygon feature:

Vectorization converts each distinct raster instance into a row in a GeoPandas GeoDataFrame. Because spatial georeferencing is transferred directly from the source GeoTIFF, these polygons can immediately be exported to GeoJSON, GeoPackage, or Shapefile formats for use in desktop GIS software.


D. Compare predictions with imagery

Before calculating statistics on vector outputs, visually inspect polygon boundaries against the original imagery using a Split-Panel Map:

Interactive split maps allow you to swipe between vector polygons and raw imagery to perform visual QA/QC checks:


E. Coordinate Reference System

Calculating real-world dimensions (e.g., area in hectares or perimeter in meters) requires verifying your dataset’s Coordinate Reference System (CRS).

Geographic CRS (Degrees)→ReprojectProjected CRS (Meters) ⟶Valid Area (ha) & Perimeter (m)\text{Geographic CRS (Degrees)} \xrightarrow{\quad \text{Reproject} \quad} \text{Projected CRS (Meters) } \longrightarrow \text{Valid Area (\text{ha}) \& Perimeter (\text{m})}

F. Compute geometric properties

With an appropriate projected CRS, add_geometric_properties() computes quantitative shape attributes for every detected polygon:

PropertyFormula / RatioSpatial & Analytical Interpretation
AreaArea in ha\text{Area in ha}Total surface area; crucial for agricultural yield forecasting and land management.
PerimeterBoundary Length in m\text{Boundary Length in m}Outer boundary length; useful for fencing, edge-effect studies, and access planning.
ElongationMajor AxisMinor Axis\frac{\text{Major Axis}}{\text{Minor Axis}}Quantifies how stretched a shape is. Differentiates compact, square parcels (1.0) from long strip fields (>3.0>3.0).
SolidityAreaConvex Hull Area\frac{\text{Area}}{\text{Convex Hull Area}}Measures boundary smoothness and convexity (1.0 = completely convex, <0.7<0.7 = highly irregular or indented boundaries).
ExtentAreaBounding Box Area\frac{\text{Area}}{\text{Bounding Box Area}}Indicates how fully a polygon fills its minimum bounding rectangle.

G. Interpreting geometric attributes

Visualizing spatial patterns based on geometric attributes turns model outputs into actionable spatial insights:

Coloring fields by area_ha or elongation exposes geographical structure across landscapes—such as large, regular parcels in flat agricultural valleys versus small, highly elongated terraced fields on hillslopes.


H. Geometry-based error diagnostics

Geometric attributes also serve as automated diagnostic tools for detecting model errors across large regional datasets:

              Quantitative Geometric Diagnostics
              
   [ Extremely Small Area ]           [ High Elongation / Low Solidity ]
   (< 0.05 ha / < 5 pixels)               (Sliver Polygon Artifacts)
               │                                      │
               ▼                                      ▼
      Fragmented Mask Error                 Boundary Splitting Error
   
   [ Extremely Large Area ]              [ Low Solidity / Indented ]
        (> 100 ha)                        (Over-merged Fields)
               │                                      │
               ▼                                      ▼
      Merged Fields Error                   Complex Boundary Artifact
:class: dropdown

Post-processing rules must adapt to the physical geometry of your target object:

* **Agricultural Fields:** Natural land parcels exhibit organic curves and irregular boundaries. Smoothing algorithms should preserve natural boundary variations without forcing right angles.
* **Building Footprints:** Man-made structures are predominantly rectilinear. Post-processing workflows for buildings typically apply **orthogonalization** algorithms to snap irregular pixel edges into $90^\circ$ right angles and straight walls.

*Never apply building orthogonalization filters to natural features like fields, water bodies, or forest patches.*

4. Common pitfalls


5. Mini task

After cleaning and vectorizing, your field dataset shows a small cluster of polygons with unusually high elongation values (around 8 to 10) in one corner of the study area, while the rest of the fields have elongation values under 3. What are two possible explanations, and how would you investigate which one applies?

Sample solution

One possibility is that these are genuinely elongated, strip-shaped fields, which do occur in some landscapes and farming traditions. Another possibility is a systematic prediction error, for example several adjacent fields being merged into one long, thin detection, or a single field being incorrectly split along its length. To investigate, you would visually compare that specific cluster against the source imagery using the split map from step C, checking whether the field boundaries visible in the imagery genuinely match the elongated shapes, or whether they suggest a merging or splitting error in the prediction.


6. Key takeaways