source: branches/0.5/win/PostNAS-0.5/bin/gdal_polygonize.py @ 23

Revision 23, 5.9 KB checked in by astrid.emde, 14 years ago (diff)
Line 
1#!/usr/bin/env python
2#******************************************************************************
3#  $Id: gdal_polygonize.py 18306 2009-12-15 18:57:11Z rouault $
4#
5#  Project:  GDAL Python Interface
6#  Purpose:  Application for converting raster data to a vector polygon layer.
7#  Author:   Frank Warmerdam, warmerdam@pobox.com
8#
9#******************************************************************************
10#  Copyright (c) 2008, Frank Warmerdam
11#
12#  Permission is hereby granted, free of charge, to any person obtaining a
13#  copy of this software and associated documentation files (the "Software"),
14#  to deal in the Software without restriction, including without limitation
15#  the rights to use, copy, modify, merge, publish, distribute, sublicense,
16#  and/or sell copies of the Software, and to permit persons to whom the
17#  Software is furnished to do so, subject to the following conditions:
18#
19#  The above copyright notice and this permission notice shall be included
20#  in all copies or substantial portions of the Software.
21#
22#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
23#  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
25#  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
27#  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
28#  DEALINGS IN THE SOFTWARE.
29#******************************************************************************
30
31try:
32    from osgeo import gdal, ogr, osr
33except ImportError:
34    import gdal, ogr, osr
35
36import sys
37import os.path
38
39def Usage():
40    print("""
41gdal_polygonize [-o name=value] [-nomask] [-mask filename] raster_file [-b band]
42                [-q] [-f ogr_format] out_file [layer] [fieldname]
43""")
44    sys.exit(1)
45
46# =============================================================================
47#       Mainline
48# =============================================================================
49
50format = 'GML'
51options = []
52quiet_flag = 0
53src_filename = None
54src_band_n = 1
55
56dst_filename = None
57dst_layername = None
58dst_fieldname = None
59dst_field = -1
60
61mask = 'default'
62
63gdal.AllRegister()
64argv = gdal.GeneralCmdLineProcessor( sys.argv )
65if argv is None:
66    sys.exit( 0 )
67
68# Parse command line arguments.
69i = 1
70while i < len(argv):
71    arg = argv[i]
72
73    if arg == '-f':
74        i = i + 1
75        format = argv[i]
76
77    elif arg == '-q' or arg == '-quiet':
78        quiet_flag = 1
79       
80    elif arg == '-nomask':
81        mask = 'none'
82       
83    elif arg == '-mask':
84        i = i + 1
85        mask = argv[i]
86       
87    elif arg == '-b':
88        i = i + 1
89        src_band_n = int(argv[i])
90
91    elif src_filename is None:
92        src_filename = argv[i]
93
94    elif dst_filename is None:
95        dst_filename = argv[i]
96
97    elif dst_layername is None:
98        dst_layername = argv[i]
99
100    elif dst_fieldname is None:
101        dst_fieldname = argv[i]
102
103    else:
104        Usage()
105
106    i = i + 1
107
108if src_filename is None or dst_filename is None:
109    Usage()
110
111if dst_layername is None:
112    dst_layername = 'out'
113   
114# =============================================================================
115#       Verify we have next gen bindings with the polygonize method.
116# =============================================================================
117try:
118    gdal.Polygonize
119except:
120    print('')
121    print('gdal.Polygonize() not available.  You are likely using "old gen"')
122    print('bindings or an older version of the next gen bindings.')
123    print('')
124    sys.exit(1)
125
126# =============================================================================
127#       Open source file
128# =============================================================================
129
130src_ds = gdal.Open( src_filename )
131   
132if src_ds is None:
133    print('Unable to open ', src_filename)
134    sys.exit(1)
135
136srcband = src_ds.GetRasterBand(src_band_n)
137
138if mask is 'default':
139    maskband = srcband.GetMaskBand()
140elif mask is 'none':
141    maskband = None
142else:
143    mask_ds = gdal.Open( mask )
144    maskband = mask_ds.GetRasterBand(1)
145
146# =============================================================================
147#       Try opening the destination file as an existing file.
148# =============================================================================
149
150try:
151    gdal.PushErrorHandler( 'QuietErrorHandler' )
152    dst_ds = ogr.Open( dst_filename, update=1 )
153    gdal.PopErrorHandler()
154except:
155    dst_ds = None
156
157# =============================================================================
158#       Create output file.
159# =============================================================================
160if dst_ds is None:
161    drv = ogr.GetDriverByName(format)
162    if not quiet_flag:
163        print('Creating output %s of format %s.' % (dst_filename, format))
164    dst_ds = drv.CreateDataSource( dst_filename )
165
166# =============================================================================
167#       Find or create destination layer.
168# =============================================================================
169try:
170    dst_layer = dst_ds.GetLayerByName(dst_layername)
171except:
172    dst_layer = None
173
174if dst_layer is None:
175
176    srs = None
177    if src_ds.GetProjectionRef() != '':
178        srs = osr.SpatialReference()
179        srs.ImportFromWkt( src_ds.GetProjectionRef() )
180       
181    dst_layer = dst_ds.CreateLayer(dst_layername, srs = srs )
182
183    if dst_fieldname is None:
184        dst_fieldname = 'DN'
185       
186    fd = ogr.FieldDefn( dst_fieldname, ogr.OFTInteger )
187    dst_layer.CreateField( fd )
188    dst_field = 0
189   
190# =============================================================================
191#       Invoke algorithm.
192# =============================================================================
193
194if quiet_flag:
195    prog_func = None
196else:
197    prog_func = gdal.TermProgress
198   
199result = gdal.Polygonize( srcband, maskband, dst_layer, dst_field, options,
200                          callback = prog_func )
201   
202srcband = None
203dst_ds = None
204
205
206
207
208
209
210
211
Note: See TracBrowser for help on using the repository browser.