Skip to content

Instantly share code, notes, and snippets.

@whitelynx
Created February 6, 2014 21:57
Show Gist options
  • Save whitelynx/8853292 to your computer and use it in GitHub Desktop.
Save whitelynx/8853292 to your computer and use it in GitHub Desktop.
A simple (slightly broken) implementation of writing a VRT file from Python, using GDAL.
#!/usr/bin/env python2
"""A simple (slightly broken) implementation of writing a VRT file from Python, using GDAL.
Adapted from sample code at: http://gis.stackexchange.com/questions/44003/python-equivalent-of-gdalbuildvrt#answer-44048
"""
## Options ##
x_size, y_size = 512, 512
source_path = 'test.tif'
source_band = 1
x_source_size, y_source_size = 256, 256
x_block, y_block = 256, 16
x_offset, y_offset = 0, 0
dest_x_offset, dest_y_offset = 0, 0
x_dest_size, y_dest_size = 512, 512
## Adapted sample code ##
from osgeo import gdal
drv = gdal.GetDriverByName("VRT")
vrt = drv.Create("test.vrt", x_size, y_size, 0)
vrt.AddBand(gdal.GDT_Float32)
band = vrt.GetRasterBand(1)
# Changed `x_size` and `y_size` to `x_source_size` and `y_source_size` on the "SourceProperties" line, since the
# `RasterXSize` and `RasterYSize` attributes should correspond to this source file's pixel size.
simple_source = '<SourceFilename relativeToVRT="1">%s</SourceFilename>' % source_path + \
'<SourceBand>%i</SourceBand>' % source_band + \
'<SourceProperties RasterXSize="%i" RasterYSize="%i" DataType="Real" BlockXSize="%i" BlockYSize="%i"/>' % (x_source_size, y_source_size, x_block, y_block) + \
'<SrcRect xOff="%i" yOff="%i" xSize="%i" ySize="%i"/>' % (x_offset, y_offset, x_source_size, y_source_size) + \
'<DstRect xOff="%i" yOff="%i" xSize="%i" ySize="%i"/>' % (dest_x_offset, dest_y_offset, x_dest_size, y_dest_size)
band.SetMetadataItem("SimpleSource", simple_source)
# Changed from an integer to a string, since only strings are allowed in `SetMetadataItem`.
band.SetMetadataItem("NoDataValue", '-9999')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment