import os
import numpy as np
import matplotlib.pyplot as plt
import geopandas as gpd
import rioxarray as rioxr17 rioxarray
In this lesson we will introduce rioxarray, a Python extension for xarray to manipulate xarray.DataArrays as rasters. The name rioxarray stands for raster input/output + xarray.
We will use rioxarray’s rio accessor to obtain raster information from an xarray.DataArray and do some raster manipulations (calculate NDVI).
By the end of this lesson, students will be able to:
- open a GeoTIFF file as an
xarray.DataArrayusingrioxarray - remove a dimension of length 1 and its coordinate from an
xarray.DataArray - use the
.rioaccessor to examine a raster’s number of bands, height, width, bounding box and CRS - plot a three-band raster as an RGB image
- clip a raster to the bounding box of an area of interest after matching their CRSs
- calculate NDVI using raster math and explain how the data type of a raster can silently give wrong results
About the data
The raster files we will use today come from the US National Agriculture Imagery Program (NAIP). NAIP images are high-resolution aerial images with four spectral bands: red (R), green (G), blue (B) and near-infrared (NIR). The rasters we’ll use today were flown on July 24, 2018.
The data used in this lesson was pre-processed from a complete NAIP scene to separate the RGB bands from the NIR band and reduce the spatial extent. The data was accessed through Microsoft’s Planetary Computer NAIP data repository [1]. The original scene is ca_m_3411935_sw_11_060_20180724_20190209.
Import a TIF file
Let’s start by loading the libraries we will use:
There are multiple ways of opening a TIF file using xarray or rioxarray. Using the rioxarray.open_rasterio() function to open the TIF file is a simple way to import the raster file as an xarray.DataArray and make sure all our geospatial data gets loaded correctly:
# Import NIR TIF file
fp = os.path.join('data','NAIP_SB_nir.tif')
nir = rioxr.open_rasterio(fp)
nir<xarray.DataArray (band: 1, y: 3208, x: 2419)> Size: 8MB
[7760152 values with dtype=uint8]
Coordinates:
* band (band) int64 8B 1
* x (x) float64 19kB 2.512e+05 2.512e+05 ... 2.527e+05 2.527e+05
* y (y) float64 26kB 3.813e+06 3.813e+06 ... 3.811e+06 3.811e+06
spatial_ref int64 8B 0
Attributes:
AREA_OR_POINT: Area
scale_factor: 1.0
add_offset: 0.0Notice we see all the components of an xarray.DataArray: its dimensions (band, y, x), the coordinates for each dimension, and some attributes. We can also directly access some of these attributes:
print('Shape: ', nir.shape)
print('Data type: ', nir.dtype, '\n')Shape: (1, 3208, 2419)
Data type: uint8
Using the .values attribute we can retrieve the underlying numpy.ndarray holding the values of the variable:
print(type(nir.values))
nir.values<class 'numpy.ndarray'>
array([[[167, 164, 161, ..., 147, 152, 151],
[170, 170, 168, ..., 151, 149, 154],
[176, 177, 177, ..., 151, 151, 151],
...,
[ 94, 88, 101, ..., 83, 88, 79],
[108, 95, 103, ..., 92, 91, 75],
[ 94, 90, 104, ..., 87, 88, 82]]], dtype=uint8)
We can also plot our data:
nir.plot()
Notice the coordinates on the x and y axes.
This map shows the light captured in the near-infrared spectrum by a sensor on a plane. Can you guess where this is? If you guessed Santa Barbara downtown, you guessed right!
Drop a dimension
Notice that our raster has an unnecessary extra dimension: band.
print("Sizes of dimensions:", dict(nir.sizes))Sizes of dimensions: {'band': 1, 'y': 3208, 'x': 2419}
This is making this xarray.DataArray three-dimensional when it is not needed. We can “squeeze this dimension” of length 1 using the squeeze() method. We pass it the name of the dimension we want to remove, in this case ‘band’, and drop=True to also get rid of the coordinate associated with this dimension.
Let’s do this:
# Original dimensions and coordinates
print(nir.dims, nir.coords,'\n')
# Remove length 1 dimension (band) and its coordinate
nir = nir.squeeze('band', drop=True)
print(nir.dims, nir.coords)('band', 'y', 'x') Coordinates:
* band (band) int64 8B 1
* x (x) float64 19kB 2.512e+05 2.512e+05 ... 2.527e+05 2.527e+05
* y (y) float64 26kB 3.813e+06 3.813e+06 ... 3.811e+06 3.811e+06
spatial_ref int64 8B 0
('y', 'x') Coordinates:
* x (x) float64 19kB 2.512e+05 2.512e+05 ... 2.527e+05 2.527e+05
* y (y) float64 26kB 3.813e+06 3.813e+06 ... 3.811e+06 3.811e+06
spatial_ref int64 8B 0
rio accessor
Remember an accessor in Python lets us access a different set of properties of an object. We have previously used accessors like .str and .dt in pandas to work with strings and dates. In this lesson, we will use the .rio accessor for an xarray.DataArray to access its raster properties. For example, we can access the number of bands, height, width, spatial bounding box, and CRS:
# Examine raster attributes using rio accessor
print('Number of bands: ', nir.rio.count)
print('Height: ', nir.rio.height)
print('Width: ', nir.rio.width, '\n')
print('Spatial bounding box: ')
print(nir.rio.bounds(), '\n')
print('CRS: ', nir.rio.crs)Number of bands: 1
Height: 3208
Width: 2419
Spatial bounding box:
(251218.8, 3811027.2, 252670.19999999998, 3812952.0)
CRS: EPSG:26911
Multi-band raster
Let’s now import the RGB raster:
# Import RGB raster
fp = os.path.join('data','NAIP_SB_rgb.tif')
rgb = rioxr.open_rasterio(fp)
rgb<xarray.DataArray (band: 3, y: 3208, x: 2419)> Size: 23MB
[23280456 values with dtype=uint8]
Coordinates:
* band (band) int64 24B 1 2 3
* x (x) float64 19kB 2.512e+05 2.512e+05 ... 2.527e+05 2.527e+05
* y (y) float64 26kB 3.813e+06 3.813e+06 ... 3.811e+06 3.811e+06
spatial_ref int64 8B 0
Attributes:
AREA_OR_POINT: Area
scale_factor: 1.0
add_offset: 0.0Notice this raster has three bands, instead of one. This makes sense because we know these bands correspond to the red, green and blue bands of the image.
Obtain the following information about the RGB raster: shape, number of bands, data type of its values and CRS.
Finally, let’s plot this raster. Since it has three bands, we can plot it as an image using the .plot.imshow() method, which will interpret the three bands of the object as RGB.
# Plot three bands as RGB image
rgb_aspect_ratio = rgb.rio.width / rgb.rio.height # Raster's aspect ratio
rgb.plot.imshow(figsize=(8*rgb_aspect_ratio,8)) # (width, height) in inches
Clip a raster
Our area of interest (AOI) for this lesson is a smaller region that includes only a few blocks around the NCEAS building. This is outlined in a GeoJSON file:
fp = os.path.join('data', 'SB_aoi.geojson')
aoi = gpd.read_file(fp)
aoi.plot()
Remember: if two geospatial datasets will interact they need to be in the same CRS. In our case, the AOI geopandas.GeoDataFrame does not have the same CRS as the rasters:
# Examine CRSs
print('aoi CRS: ', aoi.crs)
print('nir CRS: ', nir.rio.crs)
print('rgb CRS: ', rgb.rio.crs)aoi CRS: EPSG:4326
nir CRS: EPSG:26911
rgb CRS: EPSG:26911
So let’s reproject:
# Reproject AOI to RGB CRS
aoi = aoi.to_crs(rgb.rio.crs)
assert aoi.crs == rgb.rio.crsAnd plot them together:
# Plot of RGB raster with AOI overlay
fig, ax = plt.subplots(figsize=(8 * rgb_aspect_ratio, 8))
rgb.plot.imshow(ax=ax)
aoi.plot(ax=ax, alpha=0.6)
plt.show()
To clip the raster to the AOI’s bounding box we use the .rio.clip_box() method:
# Clip rasters to AOI
rgb_small = rgb.rio.clip_box(*aoi.total_bounds)
nir_small = nir.rio.clip_box(*aoi.total_bounds)Notice a few things:
- we had to use the
.rioaccessor to access theclip_box()method .rio.clip_box()usual parameters areminx,miny,maxx,maxy, the same four values thetotal_boundsattribute gave us when we clipped with a bounding box usinggpd.clip(). We are using the*asterisk as an unpacking operator to get these from the arrayaoi.total_bounds..rio.clip_box()keeps everything inside the AOI’s bounding box, not only the AOI itself. To clip a raster to the exact outline of the AOI we can use.rio.clip()with the AOI’s geometry:nir.rio.clip(aoi.geometry).
Let’s check our clipped data:
# Examine clipped data
print('Original shape: ', nir.shape)
print('Clipped shape: ', nir_small.shape)
nir_small.plot()Original shape: (3208, 2419)
Clipped shape: (1710, 1995)

Examine the same updates for the RGB data.
Raster math
We often want to perform calculations on rasters to create a new output raster, commonly known as “raster math”.
In our case, we are interested in computing the Normalized Difference Vegetation Index (NDVI) over our AOI. The NDVI is an index commonly used to check if an area has live green vegetation or not.
According to NASA’s Earth Observatory [2], NDVI values always range from -1 to 1, and areas with no green leaves give values close to zero. Typical values for different surfaces are:
Very low values of NDVI (0.1 and below) correspond to barren areas of rock, sand, or snow. Moderate values represent shrub and grassland (0.2 to 0.3), while high values indicate temperate and tropical rainforests (0.6 to 0.8).
Water and many artificial surfaces, like roofs and pavement, often have NDVI values close to zero or negative.
The NDVI is calculated using the NIR and red bands. The formula is
\(NDVI = \frac{NIR - Red}{NIR + Red}.\)
First, let’s select the red band:
# Select dimension by name and coordinate by label
red_small = rgb_small.sel(band=1)
red_small<xarray.DataArray (y: 1710, x: 1995)> Size: 3MB
[3411450 values with dtype=uint8]
Coordinates:
band int64 8B 1
* x (x) float64 16kB 2.513e+05 2.513e+05 ... 2.525e+05 2.525e+05
* y (y) float64 14kB 3.813e+06 3.813e+06 ... 3.812e+06 3.812e+06
spatial_ref int64 8B 0
Attributes:
AREA_OR_POINT: Area
scale_factor: 1.0
add_offset: 0.0We can perform raster calculations using the same arithmetic we use for numpy.ndarrays (because, underneath it all, that’s what they are).
Before we calculate the NDVI, make a prediction. Our area of interest is downtown Santa Barbara. About what share of the area do you expect to have positive NDVI values? What values do you expect for roofs and streets?
So our NDVI calculation is as follows:
ndvi = (nir_small - red_small)/(nir_small + red_small)
ndvi.plot()
Do these results look as expected? Remember that NDVI values must be between -1 and 1. Let’s check the range of our results:
print('Minimum NDVI:', ndvi.min().values)
print('Maximum NDVI:', ndvi.max().values)Minimum NDVI: 0.0
Maximum NDVI: inf
None of the values are negative and some are infinite, so something went wrong.
Data type issues
The uint8 (8-bit unsigned integer) is a very small data type that only holds integers from 0 up to 255. In particular, calculations don’t return what we are used to when working with integers (they’re done modulo 256):
np.uint8(150) + np.uint8(150)/var/folders/g8/f3j5vysd4pn88krh3zc0qv_h0000gn/T/ipykernel_36269/1890984988.py:1: RuntimeWarning: overflow encountered in scalar add
np.uint8(150) + np.uint8(150)
44
In the NDVI formula we have to subtract and add the NIR and red values, and both operations can go outside the uint8 range:
- when NIR + Red is greater than 255, the sum wraps around to a small number;
- when Red is greater than NIR, NIR - Red should be negative, but
uint8cannot hold negative numbers, so the result wraps around to a large positive number.
Notice that when we performed the NDVI calculation we did not get any warning, although the computation wrapped around on many cells. This is an example of what is referred to as a silent failure in programming, where we don’t get any warnings about the errors or unexpected behavior in our computation. That’s why it’s so important to double-check our results!
Updating data types
To be able to perform the calculation successfully, we will need to update the data type of our rasters to int16, which will be big enough to hold all the numbers that appear in the calculations:
# Update data type to int16 to perform NDVI calculation
red16 = red_small.astype('int16')
nir16 = nir_small.astype('int16')
print('RED: original dtype:', rgb_small.dtype, '.... converted dtype:', red16.dtype)
print('NIR: original dtype:', nir.dtype, '.... converted dtype:', nir16.dtype)
# Calculate NDVI
ndvi = (nir16 - red16)/(nir16+red16)
# Plot
fig, ax = plt.subplots() # Create figure and axes
ndvi.plot(
ax=ax,
cmap="RdYlGn", # Colormap for NDVI
vmin=-1, # Minimum value
vmax=1, # Maximum value
cbar_kwargs={"label": "NDVI"} # Label for color bar
)
ax.set_title("Normalized Difference Vegetation Index\nnear Santa Barbara Courthouse") # Add title
# Remove axes ticks
ax.set_xticks([])
ax.set_yticks([])
# Remove axes labels
ax.set_xlabel("")
ax.set_ylabel("")
plt.show()RED: original dtype: uint8 .... converted dtype: int16
NIR: original dtype: uint8 .... converted dtype: int16

In this image, vegetation shows up as the highest NDVI values, roughly between 0.25 and 0.6. Can you spot the Santa Barbara Courthouse?
A city planner wants to use this NDVI map to find blocks that need more street trees. Write two or three sentences on what this map can and can’t tell them.
Converting the rasters to int16 fixed the calculation, but the final map still has limits:…it shows a single summer day in 2018, and its values are 8-bit brightness values from a camera, not physical measurements of reflected light. A result that looks right is not the same as a result that is right, so always check your outputs against what you know about the data!