Raster Processing in Python: Rasterio, Xarray, and NDVI from Code

Raster Processing in Python: Rasterio, Xarray, and NDVI from Code

A colleague once spent three days computing a vegetation index for forty satellite scenes, clicking through the same raster calculator dialog forty times, and saving each result by hand. On the second afternoon he discovered that scene number 17 had been processed with the wrong band, and nobody could tell which of the others might have the same problem. He had no record of what he had done. A week later he rewrote the whole thing as a Python script of about thirty lines. It ran in four minutes, it logged every step, and when new scenes arrived the following month, he ran it again without thinking.

That is the case for processing rasters with code. Satellite images, elevation models and climate grids are arrays of numbers, and Python is superb with arrays. In this guide I’ll show you how to read, inspect, calculate with, clip, reproject and write rasters using Rasterio and NumPy, how to work with whole stacks and time series using Xarray and rioxarray, and how to compute NDVI from code, step by step, with the preparation steps and the traps that most tutorials skip.

This is the code-oriented companion to the desktop tutorial in NDVI Explained: Vegetation Analysis Step by Step in QGIS and ArcGIS Pro. If the concepts of bands, resolution and reflectance are new, read Remote Sensing Basics for GIS Users and Vector vs. Raster Data: The Complete Guide first. For Python basics, see Python for GIS: Getting Started.

Diagram: A raster script opens the file, reads the bands, masks no-data, computes the index and writes a georeferenced result.
A raster script opens the file, reads the bands, masks no-data, computes the index and writes a georeferenced result.

What a Raster Looks Like to Python

A raster is a grid of cells, each holding a value, plus georeferencing information that says where the grid sits on the Earth. In Python, these two parts are kept separately.

  • The data: a NumPy array. A single-band raster is a 2D array (rows by columns). A multi-band raster is a 3D array (bands by rows by columns).
  • The georeferencing: the CRS (coordinate reference system), the affine transform that maps array positions (row, column) to map coordinates, and the NoData value.

Rasterio reads both, and keeps them together so that you can write a result with the right location. Xarray goes further and labels the axes with coordinates, so you can select data by place and time instead of by position.


Rasterio: The Essentials

Opening and inspecting

import rasterio

with rasterio.open("dem.tif") as src:
    print(src.driver)          # file format, e.g. GTiff
    print(src.crs)             # coordinate reference system
    print(src.transform)       # affine transform: pixel size and origin
    print(src.width, src.height, src.count)   # columns, rows, bands
    print(src.dtypes)          # data type of each band
    print(src.nodata)          # the NoData value
    print(src.bounds)          # the extent
    print(src.res)             # pixel size (x, y)

The with block closes the file automatically. Always check CRS, NoData, data type and resolution before computing. These four things explain most raster problems.

Reading data

with rasterio.open("dem.tif") as src:
    band1 = src.read(1)                    # band 1 as a 2D NumPy array
    masked = src.read(1, masked=True)      # a masked array: NoData cells are masked
    profile = src.profile                  # metadata to reuse when writing

Use masked=True (or handle NoData yourself) so that NoData cells do not pollute your statistics. An elevation model with NoData of -9999 will otherwise report a minimum of -9999.

Reading part of a raster: windows

Big rasters may not fit in memory. Read a piece at a time:

from rasterio.windows import Window

with rasterio.open("big_image.tif") as src:
    window = Window(col_off=0, row_off=0, width=1024, height=1024)
    tile = src.read(1, window=window)

Rasterio can also iterate over a file’s natural blocks (src.block_windows()), which is efficient for processing huge files chunk by chunk.

Writing a raster

import numpy as np

with rasterio.open("dem.tif") as src:
    data = src.read(1).astype("float32")
    profile = src.profile

profile.update(dtype="float32", count=1, nodata=-9999, compress="deflate")

with rasterio.open("dem_float.tif", "w", **profile) as dst:
    dst.write(data, 1)

Reusing the profile copies the CRS, transform and size, so the output lines up with the input. Set the data type, the NoData value and the compression deliberately. For the formats and their trade-offs, see Shapefile vs. GeoJSON vs. GeoPackage: Which Format to Use?, which includes GeoTIFF notes.


NDVI From Code: Step by Step

Let’s compute the index that we described in the desktop tutorial. We will use a Sentinel-2 Level-2A scene, where the red band is B04 and the near-infrared band is B08, both at 10 meters. See Satellite Imagery Sources: Free vs. Paid for where to get data.

Illustration: Raster formats differ on whether the origin is the pixel centre or corner, which can shift data by half a pixel.
Raster formats differ on whether the origin is the pixel centre or corner, which can shift data by half a pixel.

The formula

NDVI = (NIR – Red) / (NIR + Red)

Step 1: Read the bands

import numpy as np
import rasterio

with rasterio.open("B04.tif") as red_src, rasterio.open("B08.tif") as nir_src:
    red_raw = red_src.read(1)
    nir_raw = nir_src.read(1)
    profile = red_src.profile

print(red_raw.dtype, nir_raw.dtype)       # often uint16

Step 2: Convert to float, always

This is the single most important line, and the cause of the most baffling bugs. Satellite bands are usually stored as unsigned 16-bit integers (uint16). If you subtract one from another in that type, a negative result wraps around to a huge positive number:

red = np.array([3000], dtype=np.uint16)
nir = np.array([2000], dtype=np.uint16)
print(nir - red)                  # [64536], not -1000!

Convert to floating point before any arithmetic:

red = red_raw.astype("float32")
nir = nir_raw.astype("float32")

Step 3: Convert to reflectance, with scale and offset

Surface reflectance is often stored as scaled integers. NDVI is a ratio, so a pure scale factor cancels out, but an offset does not. For Sentinel-2 Level-2A products processed with baseline 04.00 or later, a radiometric offset of 1,000 is applied, and reflectance equals (stored value minus 1,000) divided by 10,000. For Landsat Collection 2 Level-2 products, reflectance equals the stored value times 0.0000275, minus 0.2. Always read the product’s metadata, and apply the right conversion, especially when comparing dates or mixing product versions:

# Sentinel-2 L2A, processing baseline 04.00 or later (check your metadata)
red = (red - 1000) / 10000
nir = (nir - 1000) / 10000

Step 4: Handle NoData and division by zero

Where the sum of the bands is zero, or where the data is missing, NDVI is undefined. Handle it explicitly:

with np.errstate(divide="ignore", invalid="ignore"):
    ndvi = (nir - red) / (nir + red)

# Where there is no data, set NDVI to a NoData value
valid = (nir + red) != 0
ndvi = np.where(valid, ndvi, -9999).astype("float32")

If your bands have their own NoData value, such as 0, mask those cells too:

nodata_mask = (red_raw == 0) | (nir_raw == 0)    # uses the raw arrays read in Step 1
ndvi[nodata_mask] = -9999

Step 5: Mask clouds with the Scene Classification Layer

Sentinel-2 Level-2A includes an SCL band at 20 meters. Clouds and shadows would otherwise corrupt the result. Resample the SCL to the 10-meter grid, or read it at the target size:

from rasterio.enums import Resampling

with rasterio.open("SCL.tif") as scl_src:
    scl = scl_src.read(
        1,
        out_shape=(red.shape[0], red.shape[1]),     # match the 10 m grid
        resampling=Resampling.nearest               # categories: never interpolate
    )

# Keep vegetation (4), bare soil (5), water (6), unclassified (7)
# Remove cloud shadow (3), clouds (8, 9) and thin cirrus (10)
bad = np.isin(scl, [3, 8, 9, 10])
ndvi[bad] = -9999

Use nearest neighbor resampling for categorical layers. Interpolating class codes creates meaningless values. The same logic applies to land cover maps. See Land Use and Land Cover Classification Guide.

Step 6: Write the result

profile.update(
    dtype="float32",
    count=1,
    nodata=-9999,
    compress="deflate",
    tiled=True
)

with rasterio.open("ndvi.tif", "w", **profile) as dst:
    dst.write(ndvi, 1)

Step 7: Look at it

import matplotlib.pyplot as plt

plot_data = np.ma.masked_equal(ndvi, -9999)
plt.figure(figsize=(8, 8))
plt.imshow(plot_data, cmap="RdYlGn", vmin=-0.2, vmax=0.9)
plt.colorbar(label="NDVI")
plt.axis("off")
plt.show()

Open the same file in a desktop GIS and compare. If the result looks wrong, check, in order: the bands, the data type, the scale and offset, NoData and the clouds. The color guidance in Color Theory for Maps explains why a green-brown ramp is appropriate.

All in one function

Wrapping the steps in a function makes it reusable for forty scenes, or four hundred:

def compute_ndvi(red_path, nir_path, out_path, offset=1000, scale=10000):
    with rasterio.open(red_path) as r, rasterio.open(nir_path) as n:
        red_raw = r.read(1)
        nir_raw = n.read(1)
        profile = r.profile

    red = (red_raw.astype("float32") - offset) / scale
    nir = (nir_raw.astype("float32") - offset) / scale

    with np.errstate(divide="ignore", invalid="ignore"):
        ndvi = (nir - red) / (nir + red)

    ndvi[(red_raw == 0) | (nir_raw == 0) | ~np.isfinite(ndvi)] = -9999

    profile.update(dtype="float32", count=1, nodata=-9999, compress="deflate")
    with rasterio.open(out_path, "w", **profile) as dst:
        dst.write(ndvi.astype("float32"), 1)

And a loop over many scenes:

from pathlib import Path

for scene in sorted(Path("scenes").iterdir()):
    compute_ndvi(scene / "B04.tif", scene / "B08.tif", Path("ndvi") / f"{scene.name}_ndvi.tif")
    print("done:", scene.name)

This is the thirty-line version of my colleague’s three days.


Clipping and Reprojecting With Rasterio

Clip to a polygon

import geopandas as gpd
import rasterio
from rasterio.mask import mask

aoi = gpd.read_file("study_area.gpkg")

with rasterio.open("ndvi.tif") as src:
    aoi = aoi.to_crs(src.crs)                    # same CRS as the raster!
    clipped, transform = mask(src, aoi.geometry, crop=True, nodata=-9999)
    profile = src.profile

profile.update(height=clipped.shape[1], width=clipped.shape[2], transform=transform, nodata=-9999)
with rasterio.open("ndvi_clip.tif", "w", **profile) as dst:
    dst.write(clipped)

The most common failure is a CRS mismatch between the polygon and the raster, which produces an error saying that the shapes do not overlap the raster. Always reproject the vector to the raster’s CRS first. See GeoPandas and Shapely: Vector Data in Python.

Reproject a raster

from rasterio.warp import calculate_default_transform, reproject
from rasterio.enums import Resampling

dst_crs = "EPSG:32631"      # choose a CRS suited to your area

with rasterio.open("dem_wgs84.tif") as src:
    transform, width, height = calculate_default_transform(
        src.crs, dst_crs, src.width, src.height, *src.bounds
    )
    profile = src.profile
    profile.update(crs=dst_crs, transform=transform, width=width, height=height)

    with rasterio.open("dem_utm.tif", "w", **profile) as dst:
        reproject(
            source=rasterio.band(src, 1),
            destination=rasterio.band(dst, 1),
            src_transform=src.transform,
            src_crs=src.crs,
            dst_transform=transform,
            dst_crs=dst_crs,
            resampling=Resampling.bilinear      # continuous data; use nearest for categories
        )

Choose the resampling method by the type of data: bilinear or cubic for continuous values such as elevation and reflectance, nearest for categories. For terrain preparation, see Digital Elevation Models (DEM) and Terrain Analysis.


Zonal Statistics: Raster Values Per Polygon

A frequent task: the mean NDVI of each field. The rasterstats library does this neatly:

import geopandas as gpd
from rasterstats import zonal_stats

fields = gpd.read_file("fields.gpkg")          # must be in the raster's CRS
stats = zonal_stats(fields, "ndvi.tif", stats=["mean", "min", "max", "count"], nodata=-9999)

fields["ndvi_mean"] = [s["mean"] for s in stats]
fields.to_file("fields_ndvi.gpkg", driver="GPKG")

This is the code equivalent of the Zonal Statistics tools in QGIS and ArcGIS Pro, and the bridge between raster and vector worlds described in Spatial Analysis in GIS: Complete Guide.


Xarray and rioxarray: Stacks, Labels and Time Series

Rasterio is excellent for single rasters. When you work with many bands, many dates or large cubes, Xarray is a better fit. It holds multi-dimensional arrays with labeled dimensions and coordinates, such as time, band, y and x. rioxarray adds geospatial methods (CRS, clipping, reprojecting, writing) to it.

Opening a raster

import rioxarray

da = rioxarray.open_rasterio("B04.tif", masked=True)     # masked=True turns NoData into NaN
print(da)                  # dimensions, coordinates, attributes
print(da.rio.crs, da.rio.resolution())
da = da.squeeze("band", drop=True)                       # remove the band dimension for a single band

NDVI with labeled arrays

red = rioxarray.open_rasterio("B04.tif", masked=True).squeeze("band", drop=True)
nir = rioxarray.open_rasterio("B08.tif", masked=True).squeeze("band", drop=True)

red = (red.astype("float32") - 1000) / 10000
nir = (nir.astype("float32") - 1000) / 10000

ndvi = (nir - red) / (nir + red)
ndvi.name = "ndvi"

ndvi.rio.to_raster("ndvi_xr.tif", dtype="float32", compress="deflate")

The formula reads like the textbook. Because masked=True converts NoData into NaN, missing cells propagate automatically instead of silently corrupting the result.

Clip and reproject

import geopandas as gpd

aoi = gpd.read_file("study_area.gpkg").to_crs(ndvi.rio.crs)
ndvi_clip = ndvi.rio.clip(aoi.geometry, ndvi.rio.crs, drop=True)

ndvi_wgs84 = ndvi_clip.rio.reproject("EPSG:4326")

Time series: many dates in one array

Stack NDVI from many dates along a time dimension:

import pandas as pd
import xarray as xr

dates = pd.to_datetime(["2024-05-10", "2024-06-04", "2024-07-09", "2024-08-03"])
arrays = [compute_ndvi_xr(d) for d in dates]        # your own function returning one NDVI DataArray per date

cube = xr.concat(arrays, dim=pd.Index(dates, name="time"))

seasonal_mean = cube.mean(dim="time")                          # mean NDVI over the season
seasonal_max = cube.max(dim="time")                            # peak greenness (a robust composite)
region_series = cube.mean(dim=["x", "y"])                      # one value per date for the whole area
region_series.plot()                                           # a quick line chart

Selecting by label is a pleasure: cube.sel(time="2024-07"), or cube.sel(time=slice("2024-06-01", "2024-07-31")). Compositing by median or maximum over time is the standard way to remove clouds and noise. For the concepts of phenology and anomalies, see NDVI Explained: Vegetation Analysis Step by Step in QGIS and ArcGIS Pro.

Big data and lazy computation with Dask

Open data in chunks, and Xarray processes it lazily and in parallel, without loading everything into memory:

da = rioxarray.open_rasterio("huge_mosaic.tif", chunks={"x": 2048, "y": 2048}, masked=True)
result = da.mean()          # builds a plan; nothing is read yet
print(result.compute())     # now it runs, chunk by chunk

Chunking lets a laptop process rasters much larger than its memory. It requires the dask package.


Reading Cloud-Hosted Imagery With STAC

Instead of downloading whole scenes, you can search catalogs and read only the pixels you need. STAC (SpatioTemporal Asset Catalog) is the standard for describing such data, and cloud-optimized GeoTIFFs make partial reads efficient.

from pystac_client import Client

catalog = Client.open("https://earth-search.aws.element84.com/v1")

search = catalog.search(
    collections=["sentinel-2-l2a"],
    bbox=[2.0, 48.7, 2.6, 49.0],
    datetime="2024-06-01/2024-08-31",
    query={"eo:cloud_cover": {"lt": 20}},
)

items = search.item_collection()
print(len(items), "scenes found")
for item in items[:3]:
    print(item.id, item.properties["eo:cloud_cover"])

From the items, libraries such as stackstac and odc-stac load the bands into an Xarray cube, ready for the NDVI calculation above. Band names and the scale and offset of the values depend on the catalog, so read the item’s metadata rather than assuming. This approach is the foundation of modern cloud-native workflows, and it is also the logic behind Google Earth Engine for Beginners, but with open tools and your own control. See Geospatial Development & Automation: The Ultimate Guide for the broader picture.


Other Useful Raster Operations

Reclassify

# Slope in degrees to three classes: 0 = flat (<5), 1 = moderate (5-15), 2 = steep (>15)
classes = np.digitize(slope, bins=[5, 15])

Map algebra with conditions

suitable = (slope < 10) & (ndvi > 0.3) & (distance_to_road < 500)      # boolean array

Focal (moving window) statistics

from scipy.ndimage import uniform_filter
smooth = uniform_filter(ndvi_filled, size=3)      # 3 by 3 mean

Resample to a different resolution

with rasterio.open("B11_20m.tif") as src:
    data = src.read(
        1,
        out_shape=(src.height * 2, src.width * 2),   # 20 m to 10 m
        resampling=Resampling.bilinear
    )

Terrain derivatives

Slope, aspect and hillshade are best produced with GDAL’s gdaldem command, or libraries such as RichDEM and WhiteboxTools. See Digital Elevation Models (DEM) and Terrain Analysis and Best Free and Open-Source GIS Tools.


Common Pitfalls

  • Integer arithmetic on uint16 bands. Wrap-around and truncated division. Convert to float32 first.
  • Forgetting NoData. It biases statistics, and creates fake edges.
  • Ignoring scale factors and offsets. NDVI is sensitive to offsets, and mixing product versions creates artificial jumps.
  • Mismatched grids. A 10-meter band and a 20-meter band have different shapes. Resample explicitly, and check shapes before calculating.
  • CRS mismatch between raster and vector, causing empty or failed clips.
  • Wrong resampling method: interpolating categories, or using nearest neighbor on continuous data when reprojecting.
  • Writing the wrong data type, such as float values saved as integers, losing all decimals.
  • Not updating the profile when writing a clipped or reprojected raster, giving files that don’t line up.
  • Looping over pixels in Python. It is thousands of times slower than array operations. Use vectorized NumPy or Xarray operations.
  • Loading enormous rasters into memory. Use windows, or chunked Xarray with Dask.
  • Comparing different seasons or sensors without correction. See Satellite Imagery Sources: Free vs. Paid.
  • Trusting an index blindly. Always inspect the map, and compare with imagery.
  • Not documenting the processing, so that nobody, including you, can reproduce the result. See Metadata in GIS: Why It Matters and How to Create It.

A Reusable Workflow Pattern

Most raster projects follow the same shape:

  1. Discover and download the data, or read it from a catalog.
  2. Inspect CRS, resolution, data type, NoData and extent.
  3. Harmonize: one CRS, one grid and one resolution.
  4. Clean: mask clouds, handle NoData, apply scale and offset.
  5. Compute: indices, classifications, statistics.
  6. Summarize: by polygon or by time.
  7. Write results in a suitable format, with the right data type and metadata.
  8. Check visually, against imagery and known facts.
  9. Document and log parameters, data versions and code.

Final Thoughts

Rasters are numbers on a grid, and Python treats them as exactly that. Once you internalize a few rules, convert to float, respect NoData, match grids and CRS, choose the right resampling, a vast range of analyses opens up, from a single NDVI map to a decade of monthly composites across a continent. And because it is code, every step is recorded and repeatable.

Take a Sentinel-2 or Landsat scene for a place you know, and write the NDVI function from this guide. Run it on two dates, subtract the results, and map the difference. When the pattern of change matches what you know of the landscape, you will have crossed from clicking tools to commanding them.

Where to go next: combine rasters with databases in Spatial SQL Cheat Sheet, and connect to web data services in Intro to Web GIS APIs and OGC Standards (WMS, WFS, WMTS).

Rachid Khouri

Rachid Khouri

Rachid Khouri is a CAD, BIM and GIS professional, Autodesk Authorized Developer, trainer and technical author with more than 30 years of experience, working with AutoCAD since 1992. He founded GISauthority.com to share practical guidance on GIS and spatial technologies.