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

Revision 23, 4.8 KB checked in by astrid.emde, 14 years ago (diff)
Line 
1#!/usr/bin/env python
2###############################################################################
3# $Id: gdal2xyz.py 18215 2009-12-08 19:11:59Z rouault $
4#
5# Project:  GDAL
6# Purpose:  Script to translate GDAL supported raster into XYZ ASCII
7#           point stream.
8# Author:   Frank Warmerdam, warmerdam@pobox.com
9#
10###############################################################################
11# Copyright (c) 2002, Frank Warmerdam <warmerdam@pobox.com>
12#
13# Permission is hereby granted, free of charge, to any person obtaining a
14# copy of this software and associated documentation files (the "Software"),
15# to deal in the Software without restriction, including without limitation
16# the rights to use, copy, modify, merge, publish, distribute, sublicense,
17# and/or sell copies of the Software, and to permit persons to whom the
18# Software is furnished to do so, subject to the following conditions:
19#
20# The above copyright notice and this permission notice shall be included
21# in all copies or substantial portions of the Software.
22#
23# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
24# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
26# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
28# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
29# DEALINGS IN THE SOFTWARE.
30###############################################################################
31
32try:
33    from osgeo import gdal
34except ImportError:
35    import gdal
36
37import sys
38
39try:
40    import numpy as Numeric
41except ImportError:
42    import Numeric
43
44# =============================================================================
45def Usage():
46    print('Usage: gdal2xyz.py [-skip factor] [-srcwin xoff yoff width height]')
47    print('                   [-band b] srcfile [dstfile]')
48    print('')
49    sys.exit( 1 )
50
51# =============================================================================
52#
53# Program mainline.
54#
55
56if __name__ == '__main__':
57
58    srcwin = None
59    skip = 1   
60    srcfile = None
61    dstfile = None
62    band_nums = []
63
64    gdal.AllRegister()
65    argv = gdal.GeneralCmdLineProcessor( sys.argv )
66    if argv is None:
67        sys.exit( 0 )
68
69    # Parse command line arguments.
70    i = 1
71    while i < len(argv):
72        arg = argv[i]
73
74        if arg == '-srcwin':
75            srcwin = (int(argv[i+1]),int(argv[i+2]),
76                      int(argv[i+3]),int(argv[i+4]))
77            i = i + 4
78
79        elif arg == '-skip':
80            skip = int(argv[i+1])
81            i = i + 1
82
83        elif arg == '-band':
84            band_nums.append( int(argv[i+1]) )
85            i = i + 1
86
87        elif arg[0] == '-':
88            Usage()
89
90        elif srcfile is None:
91            srcfile = arg
92
93        elif dstfile is None:
94            dstfile = arg
95
96        else:
97            Usage()
98
99        i = i + 1
100
101    if srcfile is None:
102        Usage()
103
104    if band_nums == []: band_nums = [1]
105    # Open source file.
106    srcds = gdal.Open( srcfile )
107    if srcds is None:
108        print('Could not open %s.' % srcfile)
109        sys.exit( 1 )
110
111    bands = []
112    for band_num in band_nums:
113        band = srcds.GetRasterBand(band_num)
114        if band is None:
115            print('Could not get band %d' % band_num)
116            sys.exit( 1 )
117        bands.append(band)
118
119    gt = srcds.GetGeoTransform()
120 
121    # Collect information on all the source files.
122    if srcwin is None:
123        srcwin = (0,0,srcds.RasterXSize,srcds.RasterYSize)
124
125    # Open the output file.
126    if dstfile is not None:
127        dst_fh = open(dstfile,'wt')
128    else:
129        dst_fh = sys.stdout
130
131    band_format = ("%g " * len(bands)).rstrip() + '\n'
132
133    # Setup an appropriate print format.
134    if abs(gt[0]) < 180 and abs(gt[3]) < 180 \
135       and abs(srcds.RasterXSize * gt[1]) < 180 \
136       and abs(srcds.RasterYSize * gt[5]) < 180:
137        format = '%.10g %.10g %s'
138    else:
139        format = '%.3f %.3f %s'
140
141    # Loop emitting data.
142
143    for y in range(srcwin[1],srcwin[1]+srcwin[3],skip):
144
145        data = []
146        for band in bands:
147
148            band_data = band.ReadAsArray( srcwin[0], y, srcwin[2], 1 )   
149            band_data = Numeric.reshape( band_data, (srcwin[2],) )
150            data.append(band_data)
151
152        for x_i in range(0,srcwin[2],skip):
153
154            x = x_i + srcwin[0]
155
156            geo_x = gt[0] + (x+0.5) * gt[1] + (y+0.5) * gt[2]
157            geo_y = gt[3] + (x+0.5) * gt[4] + (y+0.5) * gt[5]
158
159            x_i_data = []
160            for i in range(len(bands)):
161                x_i_data.append(data[i][x_i])
162           
163            band_str = band_format % tuple(x_i_data)
164
165            line = format % (float(geo_x),float(geo_y), band_str)
166
167            dst_fh.write( line )
168
169
Note: See TracBrowser for help on using the repository browser.