Open In App

Opening tif file using GDAL in Python

To open a raster file we need to register drivers. In python, GDALAllRegister() is implicitly called whenever gdal is imported.

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






from osgeo import gdal, ogr

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




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.






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.




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

Output:

3
2048
1024

Article Tags :