Created
March 25, 2019 10:56
-
-
Save adriantre/7b9fc5f1d7ccfc01d5b6d11935cc3339 to your computer and use it in GitHub Desktop.
Rasterize Vector based on raster
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def RasterizeVectorFileUsingRasterFile(raster_path, vector_path, output_path): | |
raster_ds = gdal.Open(raster_path) | |
geo_transform = raster_ds.GetGeoTransform() | |
x_min = geo_transform[0] | |
y_max = geo_transform[3] | |
x_max = x_min + geo_transform[1] * raster_ds.RasterXSize | |
y_min = y_max + geo_transform[5] * raster_ds.RasterYSize | |
x_res = raster_ds.RasterXSize | |
y_res = raster_ds.RasterYSize | |
mb_v = ogr.Open(vector_path) | |
mb_l = mb_v.GetLayer() | |
pixel_width = geo_transform[1] | |
target_ds = gdal.GetDriverByName('GTiff').Create(output_path, x_res, y_res, 1, gdal.GDT_Byte) | |
target_ds.SetGeoTransform((x_min, pixel_width, 0, y_min, 0, pixel_width)) | |
target_ds.SetProjection(raster_ds.GetProjection()) | |
band = target_ds.GetRasterBand(1) | |
NoData_value = -999999 | |
band.SetNoDataValue(NoData_value) | |
band.FlushCache() | |
gdal.RasterizeLayer(target_ds, [1], mb_l) | |
target_ds = None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment