Guest User

Untitled

a guest
Sep 23rd, 2018
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. RASTERIZE_COLOR_FIELD = "__color__"
  2. RASTERIZE_COLOR = (158, 18, 110, 200)
  3.  
  4.  
  5. pixel_size = 0.05
  6.  
  7. # Open the data source
  8. orig_data_source = ogr.Open(args[0])
  9.  
  10. # Make a copy of the layer's data source because we'll need to
  11. # modify its attributes table
  12. source_ds = ogr.GetDriverByName("Memory").CopyDataSource(orig_data_source, "")
  13. source_layer = source_ds.GetLayer(0)
  14. source_srs = source_layer.GetSpatialRef()
  15. x_min, x_max, y_min, y_max = source_layer.GetExtent()
  16.  
  17. # Create the destination data source
  18. x_res = int((x_max - x_min) / pixel_size)
  19. y_res = int((y_max - y_min) / pixel_size)
  20.  
  21. # Create a field in the source layer to hold the features colors
  22. field_def = ogr.FieldDefn(RASTERIZE_COLOR_FIELD, ogr.OFTInteger)
  23. source_layer.CreateField(field_def)
  24. source_layer_def = source_layer.GetLayerDefn()
  25. field_index = source_layer_def.GetFieldIndex(RASTERIZE_COLOR_FIELD)
  26.  
  27. # Generate random values for the color field (it's here that the value
  28. # of the attribute should be used, but you get the idea)
  29. for feature in source_layer:
  30. feature.SetField(field_index, 158)
  31. source_layer.SetFeature(feature)
  32.  
  33. # Create the destination data source
  34. x_res = int((x_max - x_min) / pixel_size)
  35. y_res = int((y_max - y_min) / pixel_size)
  36.  
  37. target_ds = gdal.GetDriverByName('GTiff').Create(args[1], x_res, y_res, 4, gdal.GDT_Byte)
  38.  
  39. target_ds.SetGeoTransform((
  40. x_min, pixel_size, 0,
  41. y_max, 0, -pixel_size,
  42. ))
  43.  
  44. if source_srs:
  45. # Make the target raster have the same projection as the source
  46. target_ds.SetProjection(source_srs.ExportToWkt())
  47. else:
  48. # Source has no projection (needs GDAL >= 1.7.0 to work)
  49. target_ds.SetProjection('LOCAL_CS["arbitrary"]')
  50.  
  51. # Rasterize
  52. err = gdal.RasterizeLayer(
  53. target_ds,
  54. (4, 3, 2, 1),
  55. source_layer,
  56. burn_values=(0, 0, 0, 0),
  57. options=["ATTRIBUTE=%s" % RASTERIZE_COLOR_FIELD]
  58. )
  59.  
  60. if err != 0:
  61. raise Exception("error rasterizing layer: %s" % err)
Add Comment
Please, Sign In to add comment