Read raster data from postgis using python

In this tutorial, we will learn how to read raster data from postgis table using python.

Python is a powerful tool for raster data analysis due to rich library ecosystem: Python has a large number of libraries specifically designed for geospatial data analysis, such as rasterio, rioxarray, gdal, geopandas, shapely, etc. These libraries provide a wide range of functions and tools to work with and analyze raster data.

Read raster data from postgis using python

Before reading raster data from postgis using python, we will set up conda environment and install required python GIS packages for this task. Make sure conda is installed on your system. Use following commands to create a conda environment and to install python libraries.

Step by step tutorial for reading a raster from a PostGIS table using Python:

  1. Import necessary modules:
    • psycopg2 for connecting to the PostgreSQL database
    • for working with raster files in memory
    • rioxarray for opening and processing the raster data
  2. Configure the database connection:
    • Define the database name, username, password, host, and port.
    • Use psycopg2 to connect to the database and create a cursor.
  3. Define the table name:
    • Specify the name of the table in PostGIS that contains the raster data.
  4. Read the raster from PostGIS:
    • Use the cursor to execute a SQL query that selects the raster data using the ST_AsGDALRaster function.
    • Fetch the result using the fetchone method.
  5. Load the raster in memory:
    • Create a MemoryFile object using the result from the previous step.
    • Open the memory file using rioxarray.
  6. Read the raster in memory:
    • Use the open_rasterio method from rioxarray to read the in-memory raster data and return a Dataset object.

The raster data is now stored in the raster_dataset object and can be manipulated and processed using rioxarray.

I hope this tutorial will create a good foundation for you. If you want tutorials on another GIS topic or you have any queries, please send an email at

We also offer freelancing services. Please email us at for any query.

1 thought on “Read raster data from postgis using python”

  1. Pingback: Import rasters file to PostGIS database using raster2pgsql - Spatial Dev Guru

Leave a ReplyCancel reply