Visualizing Tiff File Using Matplotlib and GDAL using Python
Tiff file formats are used for storing raster images. A library called GDAL- Geospatial Data Abstraction Library is specially used for the purpose of reading such raster files along with other file formats like vector formats. The gdal module belongs to Open Source Geospatial Foundation
To install this module run this command into your terminal.
pip install GDAL
To visualize a tiff file we need matplotlib and GDAL modules in python.
- Import the module
- Count the number of bands.
- Fetch all the raster bands from the tiff file.
- Read the bands into NumPy arrays.
- Pass the arrays into Matplotlib’s imshow() to visualize.
The tiff file can be downloaded from here.
Step 1: Import the modules and open the file.
Step 2: Count the number of bands.
Step 3: Fetch the bands,
To fetch the bands we use GDAL’s GetRasterBand(int).
Note that the value of int we pass will always start from 1 (indexing of bands starts from 1),
Step 4: Read the bands as Numpy arrays.
GDAL provides ReadAsArray() method that converts the bands into numpy arrays and returns them.
Step 5: Plotting the arrays using imshow().
To plot the three arrays we will stack them in sequence.