Skip to content

Instantly share code, notes, and snippets.

@taylanpince
Created April 4, 2012 18:14
Show Gist options
  • Save taylanpince/2304382 to your computer and use it in GitHub Desktop.
Save taylanpince/2304382 to your computer and use it in GitHub Desktop.
Exporting raster bitmap from shape file
RASTERIZE_COLOR_FIELD = "__color__"
RASTERIZE_COLOR = (158, 18, 110, 200)
pixel_size = 0.05
# Open the data source
orig_data_source = ogr.Open(args[0])
# Make a copy of the layer's data source because we'll need to
# modify its attributes table
source_ds = ogr.GetDriverByName("Memory").CopyDataSource(orig_data_source, "")
source_layer = source_ds.GetLayer(0)
source_srs = source_layer.GetSpatialRef()
x_min, x_max, y_min, y_max = source_layer.GetExtent()
# Create the destination data source
x_res = int((x_max - x_min) / pixel_size)
y_res = int((y_max - y_min) / pixel_size)
# Create a field in the source layer to hold the features colors
field_def = ogr.FieldDefn(RASTERIZE_COLOR_FIELD, ogr.OFTInteger)
source_layer.CreateField(field_def)
source_layer_def = source_layer.GetLayerDefn()
field_index = source_layer_def.GetFieldIndex(RASTERIZE_COLOR_FIELD)
# Generate random values for the color field (it's here that the value
# of the attribute should be used, but you get the idea)
for feature in source_layer:
feature.SetField(field_index, 158)
source_layer.SetFeature(feature)
# Create the destination data source
x_res = int((x_max - x_min) / pixel_size)
y_res = int((y_max - y_min) / pixel_size)
target_ds = gdal.GetDriverByName('GTiff').Create(args[1], x_res, y_res, 4, gdal.GDT_Byte)
target_ds.SetGeoTransform((
x_min, pixel_size, 0,
y_max, 0, -pixel_size,
))
if source_srs:
# Make the target raster have the same projection as the source
target_ds.SetProjection(source_srs.ExportToWkt())
else:
# Source has no projection (needs GDAL >= 1.7.0 to work)
target_ds.SetProjection('LOCAL_CS["arbitrary"]')
# Rasterize
err = gdal.RasterizeLayer(
target_ds,
(4, 3, 2, 1),
source_layer,
burn_values=(0, 0, 0, 0),
options=["ATTRIBUTE=%s" % RASTERIZE_COLOR_FIELD]
)
if err != 0:
raise Exception("error rasterizing layer: %s" % err)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment