logo资料库

基于Python的GDAL/OGR教程:Python GDAL/OGR Cookbook.pdf

第1页 / 共64页
第2页 / 共64页
第3页 / 共64页
第4页 / 共64页
第5页 / 共64页
第6页 / 共64页
第7页 / 共64页
第8页 / 共64页
资料共64页,剩余部分请下载后查看
Table of Contents
GDAL/OGR General
Is GDAL/OGR Installed
Check Version of GDAL/OGR installed
Enable python exceptions
Install GDAL/OGR error handler
Geometry
Create a Point
Create a LineString
Create a Polygon
Create a Polygon with holes
Create a MultiPoint
Create a MultilineString
Create a MultiPolygon
Create a GeometryCollection
Create Geometry from WKT
Create Geometry from GeoJSON
Create Geometry from GML
Create Geometry from WKB
Count Points in a Geometry
Count Geometries in a Geometry
Iterate over Geometries in a Geometry
Iterate over Points in a Geometry
Buffer a Geometry
Calculate Envelope of a Geometry
Calculate the Area of a Geometry
Calculate the Length of a Geometry
Get the geometry type (as a string) from a Geometry
Calculate intersection between two Geometries
Calculate union between two Geometries
Write Geometry to GeoJSON
Write Geometry to WKT
Write Geometry to KML
Write Geometry to WKB
Force polygon to multipolygon
Quarter polygon and create centroids
Vector Layers
Delete a file
Is Ogr Installed
View Auto Generated Ogr Help
Get List of Ogr Drivers Alphabetically (A- Z)
Is Ogr Driver Available by Driver Name
Force Ogr Use Named Driver
Get Shapefile Feature Count
Get All PostGIS layers in a PostgreSQL Database
Get PostGIS Layer Feature Count By Layer Name
Get all layers in an Esri File GeoDataBase
Load data to memory
Iterate over Features
Get Geometry from each Feature in a Layer
Filter by attribute
Spatial Filter
Get Shapefile Fields - Get the user defined fields
Get Shapefile Fields and Types - Get the user definedfields
Get PostG IS Layer Fields - Get the user defined fields
Get PostGIS Layer Fields and Types - Get the user definedfields
Get a Layer's Capabilities
Get WFS layers and iterate over features
Set HTTP Proxy options before fetching a web datasource
Read a CSV of Coordinates as an OGRVRTLayer
Create a new Layer from the extent of an existing Layer
Save the convex hull of all geometry from an input Layer toan output Layer
Save centroids of input Layer to an output Layer
Create a New Shapefile and Add Data
Create a PostGIS table from WKT
Filter and Select Input Shapefile to New Output ShapefileLike ogr2ogr CLI
Merge OGR Layers
Get a list of the street names in a OSM file
Create fishnet grid
Convert polygon shapefile to line shapefile
Create point shapefile with attribute data
Create buffer
Convert vector layer to array
Convert polygon to points
Raster Layers
Close a raster dataset
Get Raster Metadata
Get Raster Band
Loop Through All Raster Bands
Get Raster Band Information
Polygonize a Raster Band
Convert an OGR File to a Raster
Clip a GeoTiff with Shapefile
Calculate zonal statistics
Raster to vector line
Create raster from array
Create least cost path
Replace No Data value of Raster with new value
Projection
Create Projection
Reproject a Geometry
Get Projection
Reproject a Layer
Export Projection
Create an ESRI.prj file
API Tricks and Trapdoors
Filtered Features Are Only Respected UsingGetNextFeature()
Iterating over features
Features and Geometries Have a Relationship You Don'tWant to Break
Welcome to the Python GDAL/OGR Cookbook! This cookbook has simple code snippets on how to use the Python GDAL/OGR API. The web site is a project at Gi tHub and served by Gi thub Pages. If you find missing recipes or mistakes in existing recipes please add an issue to the issue tracker. For a detailed description of the whole Python GDAL/OGR API, docs. see the useful API We heavily relied on Chris Garrard' s excellent Geoprocessing with Python using Open Source GIS and the official GDAL/OGR Python documentation. Another great source of examples is OGR' s autotest directory. • GDAL/OGR General o Is GDAL/OGR Installed o Check Version of GDAL/OGR installed o Enable python exceptions o Install GDAL/OGR error handler • Geometry o Create a Point o Create a LineString o Create a Polygon o Create a Polygon with holes o Create a MultiPoint o Create a MultiLineString o Create a MultiPolygon o Create a GeometryCollection o Create Geometry from WKT o Create Geometry from GeoJSON o Create Geometry from GML o Create Geometry from WKB o Count Points in a Geometry o Count Geometries in a Geometry o Iterate over Geometries in a Geometry o Iterate over Points in a Geometry o Buffer a Geometry o Calculate Envelope of a Geometry o Calculate the Area of a Geometry o Calculate the Length of a Geometry o Get the geometry type (as a string) from a Geometry o Calculate intersection between two Geometries o Calculate union between two Geometries o Write Geometry to GeoJSON o Write Geometry to WKT o Write Geometry to KML o Write Geometry to WKB o Force polygon to multipolygon o Quarter polygon and create centroids • Vector Layers o Delete a file o Is Ogr Installed
o View Auto Generated Ogr Help o Get List of Ogr Drivers Alphabetically (A- Z) o Is Ogr Driver Available by Driver Name o Force Ogr Use Named Driver o Get Shapefile Feature Count o Get All PostGIS layers in a PostgreSQL Database o Get PostGIS Layer Feature Count By Layer Name o Get all layers in an Esri File GeoDataBase o Load data to memory o Iterate over Features o Get Geometry from each Feature in a Layer o Filter by attribute o Spatial Filter o Get Shapefile Fields - Get the user defined fields o Get Shapefile Fields and Types - Get the user defined fields o Get PostGIS Layer Fields - Get the user defined fields o Get PostGIS Layer Fields and Types - Get the user defined fields o Get a Layer' s Capabilities o Get WFS layers and iterate over features o Set HTTP Proxy options before fetching a web datasource o Read a CSV of Coordinates as an OGRVRTLayer o Create a new Layer from the extent of an existing Layer o Save the convex hull of all geometry from an input Layer to an output Layer o Save centroids of input Layer to an output Layer o Create a New Shapefile and Add Data o Create a PostGIS table from WKT o Filter and Select Input Shapefile to New Output Shapefile Like ogr2ogr CLI o Merge OGR Layers o Get a list of the street names in a OSM file o Create fishnet grid o Convert polygon shapefile to line shapefile o Create point shapefile with attribute data o Create buffer o Convert vector layer to array o Convert polygon to points • Raster Layers o Close a raster dataset o Get Raster Metadata o Get Raster Band o Loop Through All Raster Bands o Get Raster Band Information o Polygonize a Raster Band o Convert an OGR File to a Raster o Clip a GeoTiff with Shapefile o Calculate zonal statistics o Raster to vector line o Create rast er from arr ay o Create l east cost pat h o Replace No Dat a Value of Raster with new value • Project i on o Create Projection
o Reproject a Geometry o Get Projection o Reproject a Layer o Export Projection o Create an ESRI.prj file • API Tricks and Trapdoors o Filtered Features Are Only Respected Using GetNextFeature() o Features and Geometries Have a Relationship You Don' t Want to Break Indices and tables • Index • Module Index • Search Page
GDAL/OGR General Is GDAL/OGR Installed Imports python GDAL and exits the program if the modules are not found. import sys try : except : from osgeo import ogr, osr, gdal sys. exit(' ERROR: cannot find GDAL/OGR modules' ) Check Version of GDAL/OGR installed This code checks the version of the GDAL/OGR on the imported module import sys from osgeo import gdal version_num = int (gdal . Versionlnfo('VERSION_NUM' )) if version_num < 1100000 : sys. exit('ERROR: Python bindings of GDAL 1.10 or later required' ) Enable python exceptions By default the GDAL/OGR Python bindings do not raise exceptions when errors occur. Instead they return an error value such as None and write an error message to sys. stdout. You can enable exceptions by calling the UseExceptions() function: from osgeo impo rt gdal # Enable GDAL/OGR exceptions gdal. UseExceptions() # open dataset that does not exist ds = gda1 . 0pen('test.tif' ) # results in python RuntimeError exception that # 'test.tif' does not exist in the file system You can disable using GDAL/OGR exceptions at any point during runtime using: from osgeo import gdal gdal. DontUseExceptions() Install GDAL/OGR error handler This recipe installs a GDAL error handler function that captures the GDAL error, class and message. Only works with GDAL version >= 1.10 try : except : from osgeo import ogr, osr, gdal
sys. exit('ERROR: cannot find GDAL/OGR modules' ) # example GDAL error handler function def gdal_error_handler (err_class, err_num, err_msg): errtype = { gdal. CE_None: 'None' , gdal. CE_Debug: 'Debug' , gdal. CE_Warning: 'Warning' , gdal. CE_Failure: 'Failure' , gdal. CE_Fatal: 'Fatal' err_msg = err_msg. replace(' \n' , ' err_class = errtype. get(err_class, 'None' ) print 'Error Number: %s' % (err_num) print 'Error Type: %s ' % (err_class) print 'Error Message: %s ' % (err_msg) ' ) if __ name __ main __ # install error handler gdal. PushErrorHandler(gdal_error_handler) # Raise a dummy error gdal. Error(l , 2, 'test error' ) #uninstall error handler gdal. PopErrorHandler()
Geometry Create a Point from osgeo import ogr point = ogr. Geometry(ogr. wkbPoint) point. AddPoint(1198054.34, 648493.09) print point. ExportToWkt() Create a LineString from osgeo import ogr line = ogr. Geometry(ogr. wkbLineString) line. AddPoint(1116651.439379124, 637392.6969887456) line. AddPoint(1188804.0108498496, 652655. 7409537067) line. AddPoint(1226730. 3625203592, 634155.0816022386) line. AddPoint(1281307. 30760719, 636467.6640211721 ) print line. ExportToWkt() Create a Polygon from osgeo import ogr # Create ring ring = ogr. Geometry(ogr. wkbLinearRing) ring. AddPoint(1179091. 1646903288, 712782.8838459781) ring. AddPoint(1161053.0218226474, 667456.2684348812) ring. AddPoint(1214704.933941905, 641092.8288590391 ) ring. AddPoint(1228580.428455506, 682719.3123998424) ring. AddPoint(1218405.0658121984, 721108. 1805541387) ring. AddPoint(1179091. 1646903288, 712782.8838459781) # Create polygon poly = ogr. Geometry(ogr. wkbPo1ygon) poly. AddGeometry(ring) print poly. ExportToWkt() Create a Polygon with holes from osgeo import ogr # Create outer ring outRing = ogr. Geometry(ogr. wkbLinearRing) outRing. AddPoint(1154115.274565847, 686419.4442701361 ) outRing. AddPoint(1154115.274565847, 653118.2574374934) outRing. AddPoint(1165678. 1866605144, 653118.2574374934) outRing. AddPoint(1165678. 1866605144, 686419.4442701361) outRing. AddPoint(1154115.274565847, 686419.4442701361 ) # Create inner ring innerRing = ogr. Geometry(ogr. wkbLinearRing) innerRing. AddPoint(1149490. 1097279799, 691044.6091080031) innerRing. AddPoint(1149490. 1097279799, 648030.5761158396) innerRing. AddPoint(1191579. 1097525698, 648030.5761158396) innerRing. AddPoint (1191579. 1097525698, 691044.6091080031 ) innerRing. AddPoint (1149490. 1097279799, 691044. 6091080031 )
# Create polygon poly = ogr. Geometry(ogr. wkbPolygon) poly. AddGeometry(outRing) poly. AddGeometry(innerRing) print poly. ExportToWkt() Create a MultiPoint from osgeo import ogr multipoint = ogr. Geometry(ogr. wkbMultiPoint) point1 = ogr. Geometry(ogr. wkbPoint) point1 . AddPoint(1251243. 7361610543, 598078. 7958668759) multipoint. AddGeometry(point1) point2 = ogr. Geometry(ogr. wkbPoint) point2. AddPoint(1240605.8570339603, 601778.9277371694) multipoint. AddGeometry(point2) point3 = ogr. Geometry(ogr. wkbPoint) point3. AddPoint(1250318. 7031934808, 606404.0925750365) multipoint. AddGeometry(point3) print multipoint. ExportToWkt() Create a MultilineString fr om osgeo impo r t ogr multiline = ogr. Geometry(ogr. wkbMultiLineString) linel = ogr. Geometry(ogr. wkbLineString) line1. AddPoint(1214242.4174581182, 617041.9717021306) line1. AddPoint(1234593. 142744733, 629529.9167643716) multiline. AddGeometry(line1) line1 = ogr. Geometry(ogr. wkbLineString) line1. AddPoint(1184641.3624957693, 626754.8178616514) line1. AddPoint(1219792.6152635587, 606866.6090588232) multiline. AddGeometry(line1) pr in t multiline. ExportToWkt() Create a MultiPolygon from osg eo imp ort ogr multipolygon = ogr. Geometry(ogr. wkbMultiPolygon) # Create ring #1 ringl = ogr. Geometry(ogr. wkbLinearRing) ring1. AddPoint(1204067.0548148106, 634617.5980860253) ring1. AddPoint(1204067.0548148106, 620742. 1035724243) ringl. AddPoint(1215167. 4504256917, 620742.1035724243) ring1. AddPoint(1215167.4504256917, 634617. 5980860253) ring1. AddPoint(1204067.0548148106, 634617. 5980860253) # Create polygon #1
poly1 = ogr. Geometry(ogr. wkbPolygon) po1yl. AddGeometry(ringl) multipolygon. AddGeometry(poly1) # Create ring #2 ring2 = ogr. Geometry(ogr. wkbLinearRing) ring2. AddPoint(1179553.6811741155, 647105.5431482664) ring2. AddPoint(1179553.6811741155, 626292.3013778647) ring2. AddPoint(1194354.20865529, 626292.3013778647) ring2. AddPoint(l194354.20865529, 647105.5431482664) ring2. AddPoint(1179553.6811741155, 647105.5431482664) # Create polygon #2 poly2 = ogr. Geometry(ogr. wkbPolygon) poly2. AddGeometry(ring2) multipolygon. AddGeometry(po1y2) print multipolygon. ExportToWkt() Create a GeometryCollection from osgeo import ogr # Create a geometry collection geomcol = ogr. Geometry(ogr. wkbGeometryCollection) # Add a point point = ogr. Geometry(ogr. wkbPoint) point. AddPoint(- 122.23, 47.09) geomcol. AddGeometry(point) # Add a line line = ogr. Geometry(ogr. wkbLineString) line. AddPoint(- 122. 60, 47. 14) line. AddPoint(- 122. 48, 47.23) geomcol. AddGeometry(line) print geomcol. ExportToWkt() Create Geometry from WKT from os ge o import ogr wkt = •poiNT (1120351. 5712494177 741921. 4223245403)" point = ogr. CreateGeometryFromWkt(wkt) print • %d, %d" % (point. GetX(), point. GetY()) Create Geometry from GeoJSON f rom os ge o import ogr geojson = '""{"type":'Point", "coordinates": [108420.33, 753808. 59]}'"" point = ogr. CreateGeometryFromJson(geojson) print • %d, %d" % (point. GetX(), point. GetY()) Create Geometry from GML fro m osgeo import ogr
分享到:
收藏