I have the following Python line to execute GDAL's rasterize function on a shapefile
subprocess.call("gdal_rasterize -te {txextent} {tyextent} -tr {resolution} -burn 1 {shapefile} {output_file}.tif")
The {output_file}
is the filename of the originally ingested input file.
I'd like to save the output_file to memory, so that I can call it down in another statement later on, for example, to upload to an S3 bucket.
How can I do this?
-
Can you do the same in actual Python code without calling a subprocess?bugmenot123– bugmenot1232022年06月08日 13:36:28 +00:00Commented Jun 8, 2022 at 13:36
-
I haven't figured out how to. The only thing which actually works for me at the moment is subprocessfuzzy_raster9873– fuzzy_raster98732022年06月08日 13:40:18 +00:00Commented Jun 8, 2022 at 13:40
1 Answer 1
Here is some code which should give you an idea of how to do it.
For gdal.Rasterize only the first two parameters are required. The rest of the parameters are **kwargs
from RasterizeOptions .
The **kwargs
will be user/project specific.
import gdal
ulx, xsize, rotx, uly, roty, ysize = geotransform # from gdal's GetGeoTransform()
XSize = 100 # Raster size in pixels (columns)
YSize = 100 # Raster size in pixels (rows)
lrx = ulx + (XSize*abs(xsize)) # Calculate the lower right x coordinate
lry = uly - (YSize*abs(ysize)) # Calculate the lower right y coordinate
outMemRas = '/vsimem/raster_name.tif'
shpFilePath = 'shapefile_path.shp'
gdal.Rasterize(outMemRas, shpFilePath,
outputType=gdal.GDT_Byte,
outputSRS='EPSG:32632',
width=XSize, height=YSize,
outputBounds=[ulx, lry, lrx, uly],
attribute='column_name',
allTouched=True)
shapeRasDS = gdal.Open(outMemRas) # Open raster file in memory with gdal
shape_arr = shapeRasDS.ReadAsArray() # Read into numpy array
gdal.Unlink(outMemRas) # remove file from memory
Explore related questions
See similar questions with these tags.