Changes between Version 14 and Version 15 of FAQRaster


Ignore:
Timestamp:
Oct 5, 2009, 11:16:01 AM (15 years ago)
Author:
Even Rouault
Comment:

Improve example thanks to Simon (Vsevolod) Ilyushchenko feedback

Legend:

Unmodified
Added
Removed
Modified
  • FAQRaster

    v14 v15  
    3030Another 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.
    3131This 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
    3332
    3433{{{
    3534#!/usr/bin/env python
    3635
    37 from osgeo import gdal
    38 from osgeo import osr
    39 from osgeo import ogr
    40 import numpy
    41 
     36try:
     37    from osgeo import gdal
     38    from osgeo import osr
     39    from osgeo import ogr
     40except:
     41    import gdal
     42    import osr
     43    import ogr
     44   
     45# To be adjusted to your needs
    4246shp = 'test.shp'
    4347tiff = 'test.tif'
    44 px = .001
    4548tiff_width = 7850
    4649tiff_height = 3500
     
    4952vector = ogr.GetDriverByName('ESRI Shapefile')
    5053src_ds = vector.Open(shp)
    51 src_lyr = src_ds.GetLayerByIndex(index=0)
     54src_lyr = src_ds.GetLayer(0)
    5255src_extent = src_lyr.GetExtent()
    5356
     
    5760
    5861# 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]
     62xres = (src_extent[1] - src_extent[0]) / tiff_width
     63yres = (src_extent[3] - src_extent[2]) / tiff_height
     64raster_transform = [src_extent[0], xres, 0.0, src_extent[3], 0.0, -yres]
    6065dst_ds.SetGeoTransform( raster_transform )
    6166
     
    6671
    6772# 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 
     73dst_ds.GetRasterBand(1).Fill(0)
     74dst_ds.GetRasterBand(2).Fill(0)
     75dst_ds.GetRasterBand(3).Fill(0)
     76dst_ds.GetRasterBand(4).Fill(255)
    7577}}}
    7678