Skip to content

Instantly share code, notes, and snippets.

@fralc
Forked from gzagatti/raster_postgis.py
Last active June 5, 2020 15:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fralc/0dad2f9ceae9909b6ba5a07b3ee3c43a to your computer and use it in GitHub Desktop.
Save fralc/0dad2f9ceae9909b6ba5a07b3ee3c43a to your computer and use it in GitHub Desktop.
Loads raster data from POSTGIS directly to numpy.array using rasterio
import psycopg2
from rasterio.io import MemoryFile
conn = pscopg2.connect("<connection string>")
cur = conn.cursor()
# ensure that the GTiff driver is available,
# see https://postgis.net/docs/postgis_gdal_enabled_drivers.html
cur.execute('''
SET postgis.gdal_enabled_drivers TO 'GTiff';
WITH temp as (
SELECT ST_Union(rast,1) As file_rast
FROM raster.table
)
SELECT ST_AsGDALRaster(file_rast, 'GTiff') FROM temp;
''')
for row in cur:
rast = row[0].tobytes()
with MemoryFile(rast).open() as dataset:
data_array = dataset.read()
print(data_array)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment