Skip to content
Related Articles

Related Articles

Improve Article

Visualizing Tiff File Using Matplotlib and GDAL using Python

  • Last Updated : 12 Nov, 2020

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. 


  1. Import the module
  2. Count the number of bands.
  3. Fetch all the raster bands from the tiff file.
  4. Read the bands into NumPy arrays.
  5. Pass the arrays into Matplotlib’s imshow() to visualize.

The tiff file can be downloaded from here.

Step-by-step implementation:

Step 1: Import the modules and open the file.


from osgeo import gdal
import matplotlib.pyplot as plt
dataset = gdal.Open(r'land_shallow_topo_2048.tif')

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), 


# since there are 3 bands
# we store in 3 different variables
band1 = dataset.GetRasterBand(1) # Red channel
band2 = dataset.GetRasterBand(2) # Green channel
band3 = dataset.GetRasterBand(3) # Blue channel

Step 4: Read the bands as Numpy arrays.

 GDAL provides ReadAsArray() method that converts the bands into numpy arrays and returns them. 


b1 = band1.ReadAsArray()
b2 = band2.ReadAsArray()
b3 = band3.ReadAsArray()

Step 5: Plotting the arrays using imshow().

To plot the three arrays we will stack them in sequence. 


img = np.dstack((b1, b2, b3))
f = plt.figure()


 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :