3

I am doing a two step process:

  1. Polygonize a PNG raster via gdal_polygonize.py
  2. Add a custom field named id
  3. Upload the resulting vector to PostGIS via ogr2ogr

I am currently doing it in two steps, like

id=e07c16a1-2de7-4221-8b18-754c5e8f07bb

gdal_polygonize.py "${id}.png" -f "ESRI Shapefile" "${id}.shp"

ogr2ogr -dialect "SQLITE" -sql "SELECT *, '${id}' AS id FROM \"${id}\"" \
    -append -f "PostgreSQL" 'PG:host={host} user={user} dbname={db}' \
    '${id}.shp' -nln {schema}."{table}" \
    --config PG_USE_COPY=YES -progress -lco PRECISION=NO

This implies writing and reading a shapefile to disk - then I need to remove the shapefile. I would like to simply pipe the output of gdal_polygonize.py into ogr2ogr so I avoid the write/read operation, which adds significance latency to the whole operation.

Something like

gdal_polygonize.py "${id}.png" "${id}.png" -f "ESRI Shapefile" /vsistdout/ | ogr2ogr ...

Is this even possible? If so, how would I read that file in the second command?

1
  • There is a format option -f also in gdal_polygonize. Write vectors directly into PostGIS and run alter table + update in the database, or with ogrinfo and -sql, as postprocess. For more sophisticated solution you should probably use Python.
    – user30184
    Commented Apr 18, 2023 at 9:48

1 Answer 1

2

I don't use PostGIS/PostgreSQL but you should be able to write directly to it from gdal_polygonize.

Alternatively, to pipe the output of gdal_polygonize to stdout, use geojson. You can't write a shapefile to stdout because it's a multi-file format.

Here is an example that writes to a shapefile, subsitute that for your postgres connection.

gdal_polygonize.py -q -of geojson -b 1 {id}.tif /vsistdout/ | ogr2ogr -dialect "SQLITE" -sql "SELECT *, '${id}' AS id FROM out"  test.shp /vsistdin/

Note:

  • I use -q to shut gdal_polygonize up as it prints progress and other info to stdout which corrupts the output
  • out is the layer name of the geojson piped from /vsistdout/ to /vsistdin/

Not the answer you're looking for? Browse other questions tagged or ask your own question.