Reputation: 13
I used following code to rasterize my polygone layer, but it gives the TypeError: in method 'Driver_Create', argument 3 of type 'int'
please let me know what is the problem and how I should solve it.
import os
from osgeo import gdal, ogr, osr
import geopandas as gpd
os.chdir('D:\\DLM_adam_paper\\forest_shp')
input_shp = ogr.Open('veg02_f.shp') # to open the shapefile using ogr
source_layer= input_shp.GetLayer() # get the layer
defn=source_layer.GetLayerDefn()
output_taster_location = 'raster\\veg02_f.tif'
pixel_size= 5
xmin, xmax, ymin, ymax= source_layer.GetExtent()
x_res=(xmax - xmin)/pixel_size # how many columns
y_res=(ymax-ymin)/pixel_size # how many rows
target_ds= gdal.GetDriverByName('GTiff').Create(output_taster_location,x_res,y_res,1,gdal.GDT_Float32,['COMPRESS=LZW'])
target_ds.SetGeoTransform((xmin,pixel_size,0.0,ymax,0.0,-pixel_size))
srse= osr.SpatialReference()
proj= 'EPSG:25832'
srse.SetWellKnownGeogCS(proj)
target_ds.SetProjection(srse.ExportToWkt())
band=target_ds.GetRasterBand(1)
target_ds.GetRasterBand(1).SetNodataValue(-9999)
band.Fill(-9999)
gdal.RasterizeLayer(target_ds, [1], source_layer, None, None, [1], option=['ALL_TOUCHED=TRUE','ATTRIBUTE=VEG'])
target_ds=None
Upvotes: 0
Views: 893
Reputation: 64463
You need to specify the dimensions of the output grid as integers, yours seem to be float. Since it comes from a Shapefile, it might be good to check if the extent matches the resolution, or otherwise think about how you want to deal with any remainder.
drv = gdal.GetDriverByName('GTiff')
ds = drv.Create(
output_taster_location,
int(x_res), # xsize
int(y_res), # ysize
1, # n_bands
gdal.GDT_Float32, # datatype
['COMPRESS=LZW'], # options
)
The expected types of the arguments are for example listed at:
https://gdal.org/api/gdaldriver_cpp.html#_CPPv4N10GDALDriver6CreateEPKciii12GDALDataType12CSLConstList
Upvotes: 0