Last active
April 29, 2024 06:51
-
-
Save gzagatti/a649674d85b480b98b7d75b31d4c9555 to your computer and use it in GitHub Desktop.
Loads raster data from POSTGIS directly to numpy.array using rasterio
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'; | |
SELECT ST_AsGDALRaster(rast, 'GTiff') FROM raster.table; | |
''') | |
for row in cur: | |
rast = row[0].tobytes() | |
with MemoryFile(rast).open() as dataset: | |
data_array = dataset.read() | |
print(data_array) |
FYI, there is a typo e.g
conn = pscopg2.connect("<connection string>")
should be
conn = psycopg2.connect("<connection string>")
AttributeError: 'NoneType' object has no attribute 'tobytes'
I am getting this error Kindly guide me
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this snippet.
In order to retrieve a tiled raster as a whole I used
ST_Union
: