In this tutorial we demonstrate how to visualize an RGB (red-green-blue) raster image using the Python library Rasterio. This library allows users to read, write, and manipulate raster or gridded geospatial data in Python.
Here we show how to open a 3-band image file (typically a GeoTiff or PNG) and display the RGB image in the notebook. We also show how to display the individual red, green, and blue channels if desired.
Import Libraries
We start by importing the necessary libraries.
import rasterio from rasterio.plot import show
Read in the Raster Image File
Now we use rasterio.open
and rasterio.read
with a specified file path (or URL) to a raster image and load it into a numpy ndarray. Here we use a GeoTIFF file named "chobe_landsat8_sample.tif" that is stored in the local EarthAI Notebook environment in a subdirectory "data". This file contains red, green, and blue bands from Landsat 8 covering a small region within the Chobe National Park.
Note this GeoTIFF, and a companion notebook that runs through the steps in this tutorial, are attached at the bottom of this page.
src = rasterio.open('data/chobe_landsat8_sample.tif') image = src.read()
Display the Image
Now we use the show
function from rasterio, passing in the image to display it. Note that this function expects the numpy array to be either a float ranging from 0 to 1, or an uint8 ranging from 0 to 255. Since our image is an uint16, we first normalize in order for it to render properly.
image_norm = (image - image.min()) / (image.max() - image.min()) show(image_norm)
It is also possible to visualize each of the three color channels of the RGB image. For this, in addition to passing in the image, you also pass in a channel number. The red channel corresponds to 1, green to 2, and blue to 3. We've added a corresponding color scheme and title just to further highlight each channel.
show((src, 1), cmap='Reds', title='Red Channel') show((src, 2), cmap='Greens', title='Green Channel') show((src, 3), cmap='Blues', title='Blue Channel')
Comments
0 comments
Please sign in to leave a comment.