| 22 | |
| 23 | == How can I create a blank raster based on a vector files extents for use with gdal_rasterize? == |
| 24 | |
| 25 | Currently the gdal_rasterize utility cannot create a blank raster based a vector datasource although this feature has been requested (ticket 1599). |
| 26 | Until that feature is add you'll need to find a way to generate a raster that matches the extent of your vector layer that you plan to use to burn features into the raster. |
| 27 | |
| 28 | One way to do this is to use gdal_translate to clip out and flatten an existing raster file that covers your area of interest. See this [http://lists.osgeo.org/pipermail/gdal-dev/2008-February/016061.html example of syntax]. |
| 29 | |
| 30 | Another approach is to use one of the language bindings to GDAL to create a blank raster from scratch. The tricky part is understanding the !GeoTransform syntax. |
| 31 | This python snippet shows how to read in a shapefile and output a tiff that matches the shapefile extents |
| 32 | * Note: you'll need to modify the `px` variable based on your desired resolution and raster dimensions |
| 33 | |
| 34 | {{{ |
| 35 | #!/usr/bin/env python |
| 36 | |
| 37 | from osgeo import gdal |
| 38 | from osgeo import osr |
| 39 | from osgeo import ogr |
| 40 | import numpy |
| 41 | |
| 42 | shp = 'test.shp' |
| 43 | tiff = 'test.tif' |
| 44 | px = .001 |
| 45 | tiff_width = 7850 |
| 46 | tiff_height = 3500 |
| 47 | |
| 48 | # Import vector shapefile |
| 49 | vector = ogr.GetDriverByName('ESRI Shapefile') |
| 50 | src_ds = vector.Open(shp) |
| 51 | src_lyr = src_ds.GetLayerByIndex(index=0) |
| 52 | src_extent = src_lyr.GetExtent() |
| 53 | |
| 54 | # Create new raster layer with 4 bands |
| 55 | raster = gdal.GetDriverByName('GTiff') |
| 56 | dst_ds = raster.Create( tiff, tiff_width, tiff_height, 4, gdal.GDT_Byte) |
| 57 | |
| 58 | # Create raster GeoTransform based on upper left corner and pixel resolution |
| 59 | raster_transform = [src_extent[0], px, 0.0, src_extent[3], 0.0, -px] |
| 60 | dst_ds.SetGeoTransform( raster_transform ) |
| 61 | |
| 62 | # Get projection of shapefile and assigned to raster |
| 63 | srs = osr.SpatialReference() |
| 64 | srs.ImportFromWkt(src_lyr.GetSpatialRef().__str__()) |
| 65 | dst_ds.SetProjection( srs.ExportToWkt() ) |
| 66 | |
| 67 | # Create blank raster with fully opaque alpha band |
| 68 | zeros = numpy.zeros( (tiff_height, tiff_width), numpy.uint8 ) |
| 69 | dst_ds.GetRasterBand(1).WriteArray( zeros ) |
| 70 | dst_ds.GetRasterBand(2).WriteArray( zeros ) |
| 71 | dst_ds.GetRasterBand(3).WriteArray( zeros ) |
| 72 | opaque = numpy.ones((tiff_height,tiff_width), numpy.uint8 )*255 |
| 73 | dst_ds.GetRasterBand(4).WriteArray( opaque ) |
| 74 | |
| 75 | }}} |
| 76 | |