Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Loads raster data from POSTGIS directly to numpy.array using rasterio
import psycopg2
from import MemoryFile
conn = pscopg2.connect("<connection string>")
cur = conn.cursor()
# ensure that the GTiff driver is available,
# see
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 =
Copy link

fralc commented Jun 5, 2020

Thanks for this snippet.
In order to retrieve a tiled raster as a whole I used ST_Union:

  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;

Copy link

ThomasG77 commented May 14, 2021

FYI, there is a typo e.g

conn = pscopg2.connect("<connection string>")

should be

conn = psycopg2.connect("<connection string>")

Copy link

Mudassir551 commented May 29, 2022

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