Hello world of raster creation with GDAL and Python

Mostly so I myself can remember how to do it, here is how to create a random geotiff with GDAL in Python

Note: the width and height are given in opposite order in the GDAL raster and numpy arrays!

import osr
import numpy
import gdal
import math
 
width = 4000
height = 3000
 
format = "GTiff"
driver = gdal.GetDriverByName( format )
 
dst_ds = driver.Create( "test.tiff", width, height, 1, gdal.GDT_Byte )
 
dst_ds.SetGeoTransform( [ 444720, 30, 0, 3751320, 0, -30 ] )
 
srs = osr.SpatialReference()
srs.ImportFromEPSG(25832)
dst_ds.SetProjection( srs.ExportToWkt() )
 
raster = numpy.zeros( (height, width), dtype=numpy.uint32 )
color_range = 2**8
seed = math.pi**10
for i in range(height):
	for j in range(width):
		color = (seed*i*j) % color_range
		raster[i][j] = color
 
dst_ds.GetRasterBand(1).WriteArray( raster )

It's kind of slow, so perhaps the operation can be speeded up somehow? The result looks kind of nice though (image created with width and height both 4000):

So, not completely random.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.