File: gdalfilter.py

package info (click to toggle)
gdal 2.4.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 106,060 kB
  • sloc: cpp: 1,034,177; ansic: 177,878; python: 23,590; perl: 7,420; sh: 6,285; java: 5,382; xml: 3,100; cs: 2,343; yacc: 1,198; makefile: 518; sql: 112
file content (179 lines) | stat: -rwxr-xr-x 5,735 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
#!/usr/bin/env python
###############################################################################
# $Id: gdalfilter.py 0abc380ee2dbc2ba4357969826ad0f9b9801b0d7 2018-05-08 22:24:06 +1000 Ben Elliston $
#
# Project:  OGR Python samples
# Purpose:  Filter an input file, producing an output file.
# Author:   Frank Warmerdam, warmerdam@pobox.com
#
###############################################################################
# Copyright (c) 2003, Frank Warmerdam <warmerdam@pobox.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
###############################################################################

import sys
from osgeo import gdal

gdal.TermProgress = gdal.TermProgress_nocb


def Usage():
    print('Usage: gdalfilter.py [-n] [-size n] [-coefs ...] [-f format] [-co NAME=VALUE]\n'
          '                     in_file out_file')
    sys.exit(1)

# =============================================================================
# 	Mainline
# =============================================================================


srcwin = None
bands = []

srcfile = None
dstfile = None
size = 3
coefs = None
normalized = 0

out_format = None
create_options = []

# Parse command line arguments.
i = 1
while i < len(sys.argv):
    arg = sys.argv[i]

    if arg == '-size':
        size = int(sys.argv[i + 1])
        i = i + 1

    elif arg == '-n':
        normalized = 1

    elif arg == '-f':
        out_format = int(sys.argv[i + 1])
        i = i + 1

    elif arg == '-co':
        create_options.append(sys.argv[i + 1])
        i = i + 1

    elif arg == '-coefs':
        coefs = []
        for iCoef in range(size * size):
            try:
                coefs.append(float(sys.argv[iCoef + i + 1]))
            except:
                print("Didn't find enough valid kernel coefficients, need ",
                      size * size)
                sys.exit(1)
        i = i + size * size

    elif srcfile is None:
        srcfile = sys.argv[i]

    elif dstfile is None:
        dstfile = sys.argv[i]

    else:
        Usage()

    i = i + 1

if dstfile is None:
    Usage()

if out_format is None and dstfile[-4:].lower() == '.vrt':
    out_format = 'VRT'
else:
    out_format = 'GTiff'

# =============================================================================
#   Open input file.
# =============================================================================

src_ds = gdal.Open(srcfile)

# =============================================================================
#   Create a virtual file in memory only which matches the configuration of
#   the input file.
# =============================================================================

vrt_driver = gdal.GetDriverByName('VRT')
vrt_ds = vrt_driver.CreateCopy('', src_ds)

# =============================================================================
#   Prepare coefficient list.
# =============================================================================
coef_list_size = size * size

if coefs is None:
    coefs = []
    for i in range(coef_list_size):
        coefs.append(1.0 / coef_list_size)

coefs_string = ''
for i in range(coef_list_size):
    coefs_string = coefs_string + ('%.8g ' % coefs[i])

# =============================================================================
#   Prepare template for XML description of the filtered source.
# =============================================================================

filt_template = \
    '''<KernelFilteredSource>
  <SourceFilename>%s</SourceFilename>
  <SourceBand>%%d</SourceBand>
  <Kernel normalized="%d">
    <Size>%d</Size>
    <Coefs>%s</Coefs>
  </Kernel>
</KernelFilteredSource>''' % (srcfile, normalized, size, coefs_string)

# =============================================================================
# Go through all the bands replacing the SimpleSource with a filtered
#       source.
# =============================================================================

for iBand in range(vrt_ds.RasterCount):
    band = vrt_ds.GetRasterBand(iBand + 1)

    src_xml = filt_template % (iBand + 1)

    band.SetMetadata({'source_0': src_xml}, 'vrt_sources')

# =============================================================================
# copy the results to a new file.
# =============================================================================

if out_format == 'VRT':
    vrt_ds.SetDescription(dstfile)
    vrt_ds = None
    sys.exit(0)

out_driver = gdal.GetDriverByName(out_format)
if out_driver is None:
    print('Output driver %s does not appear to exist.' % out_format)
    sys.exit(1)

out_ds = out_driver.CreateCopy(dstfile, vrt_ds, options=create_options,
                               callback=gdal.TermProgress)
out_ds = None