Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

Opening tif file using GDAL in Python

  • Last Updated : 12 Nov, 2020

To open a raster file we need to register drivers. In python, GDALAllRegister() is implicitly called whenever gdal is imported. The tiff file to be opened can be downloaded here.

Importing the modules: Import the gdal and ogr modules from osgeo.

 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

Python3






from osgeo import gdal, ogr

Opening the file: The raster dataset can be opened using gdal.open() by passing the filename and path. 

Python3




dataset = gdal.Open(r'land_shallow_topo_2048.tif')

Getting the metadata: We can fetch the metadata of the tif file using the GetMetadata() method.

Python3




print(dataset.GetMetadata())

Output:

{‘TIFFTAG_RESOLUTIONUNIT’: ‘2 (pixels/inch)’, ‘TIFFTAG_XRESOLUTION’: ’72’, ‘TIFFTAG_YRESOLUTION’: ’72’}

Getting other information: We can get the number of bands(represents the RGB channels) using the RasterCount() method, width of the image using RasterXSize() method and the height using RasterYSize() method.

Python3




print(dataset.RasterCount)
  
# width 
print(dataset.RasterXSize)
  
# height
print(dataset.RasterYSize)

Output:

3
2048
1024



My Personal Notes arrow_drop_up
Recommended Articles
Page :