Python与开源GIS:开始使用GDAL

导入GDAL

在Python中使用GDAL,只需要导入gdal模块。在早期的版本中,GDAL是使用下面的语句导入的:

In [1]:
import gdal

但是后来GDAL成为OSGEO的子项目后,对代码进行了重新组织。 在 RFC 17号文件中, 实现了Python的新的名称空间osgeo, 并将gdal与ogr都包含在这个名称空间之下。 现在推荐使用下面的语句导入:

In [2]:
from osgeo import gdal

当然早期版本也是支持的,但是在使用的时候会产生一个弃用警告:

为了保持兼容性,可以使用下面的语句来导入:

In [3]:
try:
    import gdal
except:
    from osgeo import gdal

除了gdal包,还有一个gdalconst包最好也导入。 gdalconst也是osgeo的一个包,它只是在代码中对GDAL中用到的一些常量进行了绑定。 其中gdalconst中的常量都加了前缀,力图与其他模块冲突最小。 所以对gdalconst你可以直接这样导入:

In [4]:
from osgeo.gdalconst import *

驱动

要读取某种类型的数据,必须要先载入数据驱动,也就是初始化一个对象,让它“知道”某种数据结构。 可以使用下面语句一次性注册所有的数据驱动,但是只能读不能写:

In [5]:
gdal.AllRegister()

单独注册某一类型的数据驱动,这样的话可以读也可以写,可以新建数据集(这最终还要取决于GDAL是否已经进行了实现)。下面的语句注册了Erdas的栅格数据类型。

In [6]:
driver = gdal.GetDriverByName('HFA')
driver.Register()
Out[6]:
5

可以使用下面的语句判断driver是否注册成功。

In [7]:
driver = gdal.GetDriverByName('GeoTiff')
driver == True
Out[7]:
False

上面的注册就失败了,因为不存在名称为“GeoTiff”的数据格式(正确的格式为“GTiff”)。

查看系统支持的数据格式

除了使用GetDriverByName(), GDAL还可以使用GetDriver()来获得驱动。 下面的代码获取了系统支持的所有的驱动的名称。

In [8]:
from osgeo import gdal
drv_count = gdal.GetDriverCount()
for idx in range(drv_count):
    driver = gdal.GetDriver(idx)
    print( "%10s: %s" % (driver.ShortName, driver.LongName))
       VRT: Virtual Raster
     GTiff: GeoTIFF
      NITF: National Imagery Transmission Format
    RPFTOC: Raster Product Format TOC format
   ECRGTOC: ECRG TOC format
       HFA: Erdas Imagine Images (.img)
  SAR_CEOS: CEOS SAR Image
      CEOS: CEOS Image
JAXAPALSAR: JAXA PALSAR Product Reader (Level 1.1/1.5)
       GFF: Ground-based SAR Applications Testbed File Format (.gff)
      ELAS: ELAS
       AIG: Arc/Info Binary Grid
   AAIGrid: Arc/Info ASCII Grid
GRASSASCIIGrid: GRASS ASCII Grid
      SDTS: SDTS Raster
      OGDI: OGDI Bridge
      DTED: DTED Elevation Raster
       PNG: Portable Network Graphics
      JPEG: JPEG JFIF
       MEM: In Memory Raster
      JDEM: Japanese DEM (.mem)
       GIF: Graphics Interchange Format (.gif)
    BIGGIF: Graphics Interchange Format (.gif)
      ESAT: Envisat Image Format
       BSB: Maptech BSB Nautical Charts
       XPM: X11 PixMap Format
       BMP: MS Windows Device Independent Bitmap
     DIMAP: SPOT DIMAP
    AirSAR: AirSAR Polarimetric Image
       RS2: RadarSat 2 XML Product
      SAFE: Sentinel-1 SAR SAFE Product
    PCIDSK: PCIDSK Database File
  PCRaster: PCRaster Raster File
     ILWIS: ILWIS Raster Map
       SGI: SGI Image File Format 1.0
   SRTMHGT: SRTMHGT File Format
  Leveller: Leveller heightfield
  Terragen: Terragen heightfield
       GMT: GMT NetCDF Grid Format
    netCDF: Network Common Data Format
      HDF4: Hierarchical Data Format Release 4
 HDF4Image: HDF4 Dataset
     ISIS3: USGS Astrogeology ISIS cube (Version 3)
     ISIS2: USGS Astrogeology ISIS cube (Version 2)
       PDS: NASA Planetary Data System
     VICAR: MIPL VICAR file
       TIL: EarthWatch .TIL
       ERS: ERMapper .ers Labelled
JP2OpenJPEG: JPEG-2000 driver based on OpenJPEG library
       L1B: NOAA Polar Orbiter Level 1b Data Set
       FIT: FIT Image
      GRIB: GRIdded Binary (.grb)
       RMF: Raster Matrix Format
       WCS: OGC Web Coverage Service
       WMS: OGC Web Map Service
      MSGN: EUMETSAT Archive native (.nat)
       RST: Idrisi Raster A.1
      INGR: Intergraph Raster
      GSAG: Golden Software ASCII Grid (.grd)
      GSBG: Golden Software Binary Grid (.grd)
     GS7BG: Golden Software 7 Binary Grid (.grd)
     COSAR: COSAR Annotated Binary Matrix (TerraSAR-X)
       TSX: TerraSAR-X Product
     COASP: DRDC COASP SAR Processor Raster
         R: R Object Data Store
       MAP: OziExplorer .MAP
KMLSUPEROVERLAY: Kml Super Overlay
      WEBP: WEBP
       PDF: Geospatial PDF
Rasterlite: Rasterlite
   MBTiles: MBTiles
  PLMOSAIC: Planet Labs Mosaics API
      CALS: CALS (Type 1)
      WMTS: OGC Web Mab Tile Service
 SENTINEL2: Sentinel 2
       MRF: Meta Raster Format
       PNM: Portable Pixmap Format (netpbm)
      DOQ1: USGS DOQ (Old Style)
      DOQ2: USGS DOQ (New Style)
    GenBin: Generic Binary (.hdr Labelled)
      PAux: PCI .aux Labelled
       MFF: Vexcel MFF Raster
      MFF2: Vexcel MFF2 (HKV) Raster
   FujiBAS: Fuji BAS Scanner Image
       GSC: GSC Geogrid
      FAST: EOSAT FAST Format
        BT: VTP .bt (Binary Terrain) 1.3 Format
       LAN: Erdas .LAN/.GIS
       CPG: Convair PolGASP
       IDA: Image Data and Analysis
       NDF: NLAPS Data Format
       EIR: Erdas Imagine Raw
     DIPEx: DIPEx
       LCP: FARSITE v.4 Landscape File (.lcp)
       GTX: NOAA Vertical Datum .GTX
    LOSLAS: NADCON .los/.las Datum Grid Shift
      NTv2: NTv2 Datum Grid Shift
   CTable2: CTable2 Datum Grid Shift
      ACE2: ACE2
    SNODAS: Snow Data Assimilation System
       KRO: KOLOR Raw
   ROI_PAC: ROI_PAC raster
      ENVI: ENVI .hdr Labelled
      EHdr: ESRI .hdr Labelled
      ISCE: ISCE raster
       ARG: Azavea Raster Grid format
       RIK: Swedish Grid RIK (.rik)
   USGSDEM: USGS Optional ASCII DEM (and CDED)
       GXF: GeoSoft Grid Exchange Format
      DODS: DAP 3.x servers
       BAG: Bathymetry Attributed Grid
      HDF5: Hierarchical Data Format Release 5
 HDF5Image: HDF5 Dataset
   NWT_GRD: Northwood Numeric Grid Format .grd/.tab
   NWT_GRC: Northwood Classified Grid Format .grc/.tab
      ADRG: ARC Digitized Raster Graphics
       SRP: Standard Raster Product (ASRP/USRP)
       BLX: Magellan topo (.blx)
   EPSILON: Epsilon wavelets
PostGISRaster: PostGIS Raster driver
      SAGA: SAGA GIS Binary Grid (.sdat)
       XYZ: ASCII Gridded XYZ
       HF2: HF2/HFZ heightfield raster
       OZI: OziExplorer Image File
       CTG: USGS LULC Composite Theme Grid
   E00GRID: Arc/Info Export E00 GRID
      ZMap: ZMap Plus Grid
  NGSGEOID: NOAA NGS Geoid Height Grids
      IRIS: IRIS data (.PPI, .CAPPi etc)
ESRI Shapefile: ESRI Shapefile
MapInfo File: MapInfo File
   UK .NTF: UK .NTF
  OGR_SDTS: SDTS
       S57: IHO S-57 (ENC)
       DGN: Microstation DGN
   OGR_VRT: VRT - Virtual Datasource
       REC: EPIInfo .REC 
    Memory: Memory
       BNA: Atlas BNA
       CSV: Comma Separated Value (.csv)
       NAS: NAS - ALKIS
       GML: Geography Markup Language (GML)
       GPX: GPX
    LIBKML: Keyhole Markup Language (LIBKML)
       KML: Keyhole Markup Language (KML)
   GeoJSON: GeoJSON
Interlis 1: Interlis 1
Interlis 2: Interlis 2
   OGR_GMT: GMT ASCII Vectors (.gmt)
      GPKG: GeoPackage
    SQLite: SQLite / Spatialite
  OGR_DODS: OGR_DODS
      ODBC: ODBC
      WAsP: WAsP .map format
      PGeo: ESRI Personal GeoDatabase
MSSQLSpatial: Microsoft SQL Server Spatial Database
  OGR_OGDI: OGDI Vectors (VPF, VMAP, DCW)
PostgreSQL: PostgreSQL/PostGIS
     MySQL: MySQL
OpenFileGDB: ESRI FileGDB
    XPlane: X-Plane/Flightgear aeronautical data
       DXF: AutoCAD DXF
Geoconcept: Geoconcept
    GeoRSS: GeoRSS
GPSTrackMaker: GPSTrackMaker
       VFK: Czech Cadastral Exchange Data Format
    PGDUMP: PostgreSQL SQL dump
       OSM: OpenStreetMap XML and PBF
  GPSBabel: GPSBabel
       SUA: Tim Newport-Peace's Special Use Airspace Format
   OpenAir: OpenAir
   OGR_PDS: Planetary Data Systems TABLE
       WFS: OGC WFS (Web Feature Service)
       HTF: Hydrographic Transfer Vector
AeronavFAA: Aeronav FAA
  Geomedia: Geomedia .mdb
    EDIGEO: French EDIGEO exchange format
       GFT: Google Fusion Tables
       SVG: Scalable Vector Graphics
   CouchDB: CouchDB / GeoCouch
  Cloudant: Cloudant / CouchDB
    Idrisi: Idrisi Vector (.vct)
    ARCGEN: Arc/Info Generate
  SEGUKOOA: SEG-P1 / UKOOA P1/90
      SEGY: SEG-Y
       XLS: MS Excel format
       ODS: Open Document/ LibreOffice / OpenOffice Spreadsheet 
      XLSX: MS Office Open XML spreadsheet
ElasticSearch: Elastic Search
      Walk: Walk
     Carto: Carto
AmigoCloud: AmigoCloud
       SXF: Storage and eXchange Format
   Selafin: Selafin
       JML: OpenJUMP JML
  PLSCENES: Planet Labs Scenes API
       CSW: OGC CSW (Catalog  Service for the Web)
       VDV: VDV-451/VDV-452/INTREST Data Format
     TIGER: U.S. Census TIGER/Line
    AVCBin: Arc/Info Binary Coverage
    AVCE00: Arc/Info E00 (ASCII) Coverage
      HTTP: HTTP Fetching Wrapper

上面第4行,直接使用了索引值来获得驱动,而在第5行则打印了驱动的名称。注意到驱动有ShortName与LongName。ShortName与栅格数据格式在GDAL中定义的编码是一致的,而LongName则可以看成是描述性的文字。 对于不同的Linux发行版,以及安装的GDAL的版本与编译选项的不同,上面程序的结果是不一样的。所以一般情况下要避免使用gdal.GetDriver()这个函数来获取驱动。 我使用的系统是Debian Squeeze,返回的驱动的个数是88。