Examples
Getting information on a raster dataset using dedicated methods
The following snippet uses individual API methods to retrieve characters of a GDAL raster dataset and its bands.
from osgeo import gdal
import json
gdal.UseExceptions()
ds = gdal.Open("data/byte.tif")
print(f"Width: {ds.RasterXSize}")
print(f"Height: {ds.RasterYSize}")
print(f"Number of bands: {ds.RasterCount}")
Width: 20
Height: 20
Number of bands: 1
srs = ds.GetSpatialRef()
srs_unit = ""
if srs:
srs_as_projjson = json.loads(srs.ExportToPROJJSON())
print("SRS:")
srs_type = srs_as_projjson["type"]
print(f" Type: {srs_type}")
name = srs_as_projjson["name"]
print(f" Name: {name}")
if "id" in srs_as_projjson:
id = srs_as_projjson["id"]
authority = id["authority"]
code = id["code"]
print(f" Id: {authority}:{code}")
srs_unit = " " + srs_as_projjson["coordinate_system"]["axis"][0]["unit"]
SRS:
Type: ProjectedCRS
Name: NAD27 / UTM zone 11N
Id: EPSG:26711
geotransform = ds.GetGeoTransform()
if geotransform[2] == 0 and geotransform[4] == 0:
print(f"Upper-left corner georeferenced position: X={geotransform[0]}{srs_unit}, Y={geotransform[3]}{srs_unit}")
print(f"Horizontal resolution: {geotransform[1]}{srs_unit}")
print(f"Vertical resolution: {geotransform[5]}{srs_unit} (negative value indicates a north-up image)")
else:
print(f"Geotransformation matrix: {geotransform}")
print(f"Metadata: {ds.GetMetadata()}")
Upper-left corner georeferenced position: X=440720.0 metre, Y=3751320.0 metre
Horizontal resolution: 60.0 metre
Vertical resolution: -60.0 metre (negative value indicates a north-up image)
Metadata: {'AREA_OR_POINT': 'Area'}
for idx, band in enumerate(ds):
print(f"Band {idx+1}:")
print(f" Data type: {gdal.GetDataTypeName(band.DataType)}")
block_width, block_height = band.GetBlockSize()
print(f" Block width: {block_width}")
print(f" Block height: {block_height}")
print(f" Metadata: {band.GetMetadata()}")
Band 1:
Data type: Byte
Block width: 20
Block height: 20
Metadata: {}
# Explicitly close the dataset. May be needed in creation/update scenarios, to
# make sure all data is properly flushed to storage, or even in read-only
# scenarios, if you want to delete the file afterwards (on Windows).
# You may also use a context manager with "with gdal.Open(...) as ds" as shown
# in later examples.
ds.Close()
Getting information on a raster dataset using gdal.Info()
The following snippet uses the osgeo.gdal.Info()
method to retrieve characters of
a GDAL raster dataset and its bands, as a JSON document.
from osgeo import gdal
import pprint
gdal.UseExceptions()
with gdal.Open("data/byte.tif") as ds:
info = gdal.Info(ds, format='json')
del info["stac"] # to avoid cluttering below output
pprint.pprint(info, indent=2, width=100)
Show code cell output
{ 'bands': [ { 'band': 1,
'block': [20, 20],
'colorInterpretation': 'Gray',
'metadata': {},
'type': 'Byte'}],
'coordinateSystem': { 'dataAxisToSRSAxisMapping': [1, 2],
'wkt': 'PROJCRS["NAD27 / UTM zone 11N",\n'
' BASEGEOGCRS["NAD27",\n'
' DATUM["North American Datum 1927",\n'
' ELLIPSOID["Clarke 1866",6378206.4,294.978698213898,\n'
' LENGTHUNIT["metre",1]]],\n'
' PRIMEM["Greenwich",0,\n'
' ANGLEUNIT["degree",0.0174532925199433]],\n'
' ID["EPSG",4267]],\n'
' CONVERSION["UTM zone 11N",\n'
' METHOD["Transverse Mercator",\n'
' ID["EPSG",9807]],\n'
' PARAMETER["Latitude of natural origin",0,\n'
' ANGLEUNIT["degree",0.0174532925199433],\n'
' ID["EPSG",8801]],\n'
' PARAMETER["Longitude of natural origin",-117,\n'
' ANGLEUNIT["degree",0.0174532925199433],\n'
' ID["EPSG",8802]],\n'
' PARAMETER["Scale factor at natural origin",0.9996,\n'
' SCALEUNIT["unity",1],\n'
' ID["EPSG",8805]],\n'
' PARAMETER["False easting",500000,\n'
' LENGTHUNIT["metre",1],\n'
' ID["EPSG",8806]],\n'
' PARAMETER["False northing",0,\n'
' LENGTHUNIT["metre",1],\n'
' ID["EPSG",8807]]],\n'
' CS[Cartesian,2],\n'
' AXIS["(E)",east,\n'
' ORDER[1],\n'
' LENGTHUNIT["metre",1]],\n'
' AXIS["(N)",north,\n'
' ORDER[2],\n'
' LENGTHUNIT["metre",1]],\n'
' USAGE[\n'
' SCOPE["Engineering survey, topographic mapping."],\n'
' AREA["North America - between 120°W and 114°W - onshore. '
'Canada - Alberta; British Columbia; Northwest Territories; '
'Nunavut. Mexico. United States (USA) - California; Idaho; Nevada; '
'Oregon; Washington."],\n'
' BBOX[26.93,-120,78.13,-114]],\n'
' ID["EPSG",26711]]'},
'cornerCoordinates': { 'center': [441320.0, 3750720.0],
'lowerLeft': [440720.0, 3750120.0],
'lowerRight': [441920.0, 3750120.0],
'upperLeft': [440720.0, 3751320.0],
'upperRight': [441920.0, 3751320.0]},
'description': 'data/byte.tif',
'driverLongName': 'GeoTIFF',
'driverShortName': 'GTiff',
'files': ['data/byte.tif'],
'geoTransform': [440720.0, 60.0, 0.0, 3751320.0, 0.0, -60.0],
'metadata': {'': {'AREA_OR_POINT': 'Area'}, 'IMAGE_STRUCTURE': {'INTERLEAVE': 'BAND'}},
'size': [20, 20],
'wgs84Extent': { 'coordinates': [ [ [-117.6420428, 33.9023684],
[-117.6419617, 33.8915461],
[-117.6289846, 33.8916131],
[-117.629064, 33.9024353],
[-117.6420428, 33.9023684]]],
'type': 'Polygon'}}
Reading a whole raster as a numpy array
The following snippet uses the osgeo.gdal.Dataset.ReadAsArray()
method to retrieve the pixel values of all the bands of a dataset as a
numpy array.
A 2D array is returned for a single band image. A 3D array, with first dimension being the band one, is returned for images with multiple bands.
from osgeo import gdal
gdal.UseExceptions()
with gdal.Open("data/byte.tif") as ds:
array = ds.ReadAsArray()
print(array)
Show code cell output
[[107 123 132 115 132 132 140 132 132 132 107 132 107 132 132 107 123 115
156 148]
[115 132 107 123 148 115 165 115 140 107 123 123 99 132 123 132 132 132
99 156]
[115 132 140 132 123 115 140 107 140 115 132 123 107 132 132 115 115 107
115 107]
[148 132 123 123 115 132 132 123 115 123 115 123 107 115 148 107 115 140
115 132]
[132 156 132 140 132 132 115 115 115 123 148 123 165 123 132 107 107 132
156 123]
[189 173 173 148 148 115 148 123 107 132 115 132 156 99 123 115 132 132
206 107]
[197 173 148 140 140 132 99 132 123 115 140 132 132 99 132 123 132 173
123 115]
[148 123 148 115 148 123 140 123 107 115 132 115 107 115 99 123 99 181
99 107]
[123 115 132 115 123 132 115 132 132 123 123 132 99 115 99 123 132 115
115 107]
[140 140 99 140 99 115 123 107 132 107 115 107 115 123 132 123 107 123
132 132]
[132 132 132 123 99 132 123 107 148 99 115 123 140 173 123 107 123 123
123 107]
[123 123 123 107 140 123 123 115 115 90 107 173 107 107 107 107 99 132
123 115]
[173 148 99 123 123 107 123 99 107 189 173 107 115 115 107 99 140 107
173 140]
[148 132 132 107 123 99 99 115 99 132 99 140 115 148 123 99 132 123
148 140]
[140 107 140 90 107 115 107 90 99 123 115 115 115 123 123 148 115 148
99 132]
[165 148 156 123 107 107 107 115 140 99 115 99 99 107 115 132 115 90
123 115]
[189 173 140 140 165 115 132 90 99 115 90 99 99 107 99 132 99 107
132 132]
[156 181 140 173 123 132 99 115 123 74 115 99 123 140 156 132 165 140
140 99]
[173 247 255 206 132 107 140 123 148 132 165 165 148 140 132 123 107 123
107 123]
[181 181 156 148 156 156 156 181 132 148 115 132 107 107 107 107 107 115
99 107]]