PostGIS导入导出栅格数据
上一篇博文PostGIS导入导出ESRI Shapefile数据介绍了如何导入空间矢量数据到PostgreSQL中,紧接上一篇,本文将介绍如何使用PostGIS导入导出空间栅格数据。 PostGIS提供了raster2pgsql工具用于栅格数据的导入(可以使用man raster2pgsql命令查看帮助文档)。 raster2pgsql -s 4326 -C ~/Downloads/gisdata/wsiearth.tif staging.wsiearth | psql -h localhost -p 5432 -U postgres -d postgis_in_action -W
如果想要导出数据,可以使用PostGIS提供的内置函数。其中ST_AsGDALRaster 是一个通用性的函数,可以导出为GDAL支持的任意格式。此外,还有ST_AsPNG,ST_AsJPEG和ST_AsTIFF等函数,提供了直接导出到指定格式,并且接受更少的参数。 sudo vim /etc/postgresql/9.5/main/postgresql.conf
在该配置文件后面添加: postgis.gdal_enabled_drivers = 'ENABLE_ALL'
postgis.enable_outdb_rasters = True
重启PostgreSQL: sudo service postgresql restart
参考链接: 第二个问题是:这些内置函数提供的导出结果是PostgreSQL的bytea (byte array)数据类型,我们需要自己写程序进行转换成实际的图像文件。 下面我使用Python的Psycopg库连接PostgreSQL数据库,进行查询并导出最终的结果。Psycopg库参见:http://initd.org/psycopg/docs/index.html。 # -*- coding: utf-8 -*-
import psycopg2
# Connect to an existing database
conn = psycopg2.connect('host=localhost port=5432 user=postgres password=password dbname=postgis_in_action')
# Open a cursor to perform database operations
cur = conn.cursor()
# Execute SQL query
cur.execute("SELECT ST_AsTIFF(rast,'LZW') AS rasttiff FROM staging.wsiearth WHERE rid=1;")
# Fetch data as Python objects
rasttiff = cur.fetchone()
# Write data to file
if rasttiff is not None:
open('/home/theone/Desktop/wsiearth.tif','wb').write(str(rasttiff[0]))
# Close communication with the database
cur.close()
conn.close()
在QGIS中查看导出结果如下: (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |