Skip to content
Related Articles

Related Articles

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.

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

from osgeo import gdal, ogr

chevron_right


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

Python3



filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

print(dataset.GetMetadata())

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

3
2048
1024

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.

My Personal Notes arrow_drop_up
Recommended Articles
Page :