Geographic Information Systems Asked on June 12, 2021
Followed the steps from this link to create raster from shapefile using GDAL
Convert an OGR File to a Raster
but it is returning an empty raster.
Can someone tell how to define a particular column from the shapefile data to burn?
The code is as follows
import gdal
from osgeo import osr
from osgeo import ogr
raster_path = 'D:SWAT_HRU_TestSWAT_BiharBihar_shapefile_pythonFull_HRU_GCS_output.tif'
shapefile = 'D:SWAT_HRU_TestSWAT_BiharBihar_shapefile_pythonFull_HRU_GCS.shp'
source_ds = ogr.Open(shapefile)
source_layer = source_ds.GetLayer()
pixelWidth = pixelHeight = 0.01
x_min, x_max, y_min, y_max = source_layer.GetExtent()
cols = int((x_max - x_min) / pixelHeight)
rows = int((y_max - y_min) / pixelWidth)
target_ds = gdal.GetDriverByName('GTiff').Create(raster_path, cols, rows, 1, gdal.GDT_Float32)
target_ds.SetGeoTransform((x_min, pixelWidth, 0, y_max, 0, -pixelHeight))
target_dsSRS = osr.SpatialReference()
target_dsSRS.ImportFromEPSG(4326)
target_ds.SetProjection(target_dsSRS.ExportToWkt())
band = target_ds.GetRasterBand(1)
band.SetNoDataValue(-9999)
gdal.RasterizeLayer(target_ds, [1], source_layer, options=["ATTRIBUTE = HRUGIS"])
### this HRUGIS is a column in the shapefile on the basis of which i want to create the raster but it is returning a raster with all values 255
target_ds = None
edit: Since GeoCube has quite some (nontrivial) dependencies, I recommend creating a new environment with:
conda create -n <your_name> -c conda-forge geocube <whatever_else>
, optionally also --strict-channel-priority
There is a great module: GeoCube, that does exactly what you want. It is somewhat more high-level, but uses GDAL internally I believe. Then, it becomes as easy as:
from geocube.api.core import make_geocube
import rioxarray
import geopandas as gpd
raster_path = 'your path'
vector_path = 'other path'
source_ds = gpd.read_file(vector_path)
DEM = rioxarray.open_rasterio(raster_path,masked=True)
Cube = make_geocube(vector_data=source_ds['columns1','columns2'],like=DEM)
Cube.columns1.plot()
alternatively, you can leave out the ['columns1','columns2']
to rasterize all attributes of the shapefile
sidenote: shapefile is the ESRI standard for storing vector formats, so I prefer to call it vector inside a program/script, since you can derive them from anywhere.
Correct answer by Gevaert Joep on June 12, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP