I have been using gdal
from the command line to convert an asc
file to a GeoJSON
output. I can do this successfully:
gdal_polygonize.py input.asc -f "GeoJSON" output.json
Now I wish to use Python and follow this process for a range of files.
import gdal
import glob
for file in glob.glob("dir/*.asc"):
new_name = file[:-4] + ".json"
gdal.Polygonize(file, "-f", "GeoJSON", new_name)
Hpwever, for exactly the same file I get the following error TypeError: in method 'Polygonize', argument 1 of type 'GDALRasterBandShadow *'
Why does the command line version work and the python version not?
The easiest way to find what is wrong with your call to gdal.Polygonize is to investigate the documentation for that function. You can find it here by going through the C algorithms API. Admittedly, GDAL's documentation isn't the most coherent and easy to access. This is doubly true for the conversion of the C API to Python.
GDALPolygonize (GDALRasterBandH hSrcBand,
GDALRasterBandH hMaskBand,
OGRLayerH hOutLayer,
int iPixValField,
char ** papszOptions,
GDALProgressFunc pfnProgress,
void * pProgressArg
)
You can see that the first two arguments are RasterBand types. The output type is an OGRLayer, and there are other (in this case unnecessary) options.
To use gdal.Polygonize()
you will need to open your input file with gdal, get a raster band, and pass that into the function. Similarly, you will need to create a new geojson vector file, and pass its layer into the function.
subprocess
As an alternative, you could employ python's subprocess
module to call the same command-line program that you already know.
import subprocess
import glob
import os
for f in glob.glob("dir/*.asc"): # don't override python's file variable
out_file = f[:-4] + ".json"
in_file = os.path.join("dir", f) # need the full path of the input
cmdline = ['gdal_polygonize.py', in_file, ,"-f", "GeoJSON", out_file]
subprocess.call(cmdline)