【问题标题】:How to query stored PostGIS Raster data from within the IPython Notebook如何从 IPython Notebook 中查询存储的 PostGIS Raster 数据
【发布时间】:2014-04-15 22:49:52
【问题描述】:

测试数据

三重目标:

  1. 使用 raster2pgsql 将栅格加载到 PostGIS 并在 QGIS 中可视化
  2. 在我的 IPython Notebook 中连接到 PostGIS 并将栅格加载到 NumPy 数组中
  3. 在我的 IPyhton Notebook 中,使用 Pandas 加载存储在 PostGIS 中的具有不同时间步长的一个像素栅格的时间序列

到目前为止的过程 我已经设法使用raster2pgsql 命令将一张光栅图像放入 PostGIS Raster,并使用 DB Manager 在 QGIS 中将其可视化:

raster2pgsql -s 4326 -d -I -C -M -R -l 4 D:\Downloads\raster//modis.tif -F -t 100x100 public.ndvi | psql -U postgres -d rastertest -h localhost -p 5432

但是如何从 IPython Notebook 中访问/查询这个栅格呢?

我发现了这个presentation,它是关于 SQLALchemy 和 GeoAlchemy2 的。并且提到它也支持 PostGIS Raster。这似乎很有趣!但是使用documentation 我不知道如何将其应用于栅格数据

我想我可以使用以下代码连接到我的 PostGIS 数据库,其中 postgres=userpassword=admindatabase=rastertest

from sqlalchemy import create_engine
engine = create_engine('postgresql://postgres:admin@localhost/rastertest', echo=True)

但是.. 非常感谢任何建议。

【问题讨论】:

  • 我不熟悉 PostGIS,但如果最终它只是普通的旧 SQL,您可能想尝试ipython-sql (pypi.python.org/pypi/ipython-sql),它允许您连接到数据库并编写在 IPython notebook 中使用 %sql 和 %%sql 魔法查询,完全避免 ORM 路由。
  • 您想在 ipython 笔记本中可视化栅格吗?

标签: postgresql pandas sqlalchemy postgis geoalchemy


【解决方案1】:

您应该使用 psycopg 模块从 python 连接到 postgres 数据库。一些代码示例:

import psycopg2


def connect_db():

try:
    conn = psycopg2.connect("dbname='rastertest' user='admin' host='localhost' password='password'")
    conn.set_session(autocommit=True) #if you want your updates to take effect without being in a transaction and requiring a commit, for a beginner, I would set this to True
    return conn
except:
    print "I am unable to connect to the database"
    return None

def get_raster(raster_id,conn):

    query= "SELECT ST_AsText(geom) from raster_table where id={}".format(raster_id)
    conn.cursor().execute(query)
    res = cur.fetchall()

    return res[0][0]

也许光栅的文本表示是您可以使用的。 或者,查看http://postgis.net/docs/RT_reference.html 以查看是否有任何函数返回您想要的 numpy 数组并相应地替换 get_raster 中的查询。 (可能是这个http://postgis.net/docs/RT_ST_DumpValues.html

【讨论】:

  • 你的帖子看起来很有趣。一定会试一试的!
猜你喜欢
  • 2015-09-24
  • 2022-01-24
  • 2014-02-27
  • 2014-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多