gdal.py 17.2 KB
Newer Older
1
2
# -*- coding: utf-8 -*-

3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# py_tools_ds
#
# Copyright (C) 2019  Daniel Scheffler (GFZ Potsdam, daniel.scheffler@gfz-potsdam.de)
#
# This software was developed within the context of the GeoMultiSens project funded
# by the German Federal Ministry of Education and Research
# (project grant code: 01 IS 14 010 A-C).
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License along
# with this program.  If not, see <http://www.gnu.org/licenses/>.

24
from __future__ import absolute_import
25
26
27
28
29
30
31
32
import os

try:
    from osgeo import gdal
except ImportError:
    import gdal

from ..processing.shell import subcall_with_output
33
from ..io.pathgen import get_tempfile
34

35
36
__author__ = "Daniel Scheffler"

37

38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
def Warp(destNameOrDestDS, srcDSOrSrcDSTab, options='', format='GTiff',
         outputBounds=None,
         outputBoundsSRS=None,
         xRes=None, yRes=None, targetAlignedPixels=False,
         width=0, height=0,
         srcSRS=None, dstSRS=None,
         srcAlpha=False, dstAlpha=False,
         warpOptions=None, errorThreshold=None,
         warpMemoryLimit=None, creationOptions=None, outputType=gdal.GDT_Unknown,
         workingType=gdal.GDT_Unknown, resampleAlg=None,
         srcNodata=None, dstNodata=None, multithread=False,
         tps=False, rpc=False, geoloc=False, polynomialOrder=None,
         transformerOptions=None, cutlineDSName=None,
         cutlineLayer=None, cutlineWhere=None, cutlineSQL=None, cutlineBlend=None, cropToCutline=False,
         copyMetadata=True, metadataConflictValue=None,
         setColorInterpretation=False,
         callback=None, callback_data=None):
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
    """ This functions brings functionality of gdal.Warp() that is not available in GDAL versions below 2.1 (?).

        Keyword arguments are :
          options --- can be be an array of strings, a string or let empty and filled from other keywords.
          format --- output format ("GTiff", etc...)
          outputBounds --- output bounds as (minX, minY, maxX, maxY) in target SRS
          outputBoundsSRS --- SRS in which output bounds are expressed, in the case they are not expressed in dstSRS
          xRes, yRes --- output resolution in target SRS
          targetAlignedPixels --- whether to force output bounds to be multiple of output resolution
          width --- width of the output raster in pixel
          height --- height of the output raster in pixel
          srcSRS --- source SRS
          dstSRS --- output SRS
          srcAlpha --- whether to force the last band of the input dataset to be considered as an alpha band
          dstAlpha --- whether to force the creation of an output alpha band
          outputType --- output type (gdal.GDT_Byte, etc...)
          workingType --- working type (gdal.GDT_Byte, etc...)
          warpOptions --- list of warping options
          errorThreshold --- error threshold for approximation transformer (in pixels)
          warpMemoryLimit --- size of working buffer in bytes
          resampleAlg --- resampling mode
          creationOptions --- list of creation options
          srcNodata --- source nodata value(s)
          dstNodata --- output nodata value(s)
          multithread --- whether to multithread computation and I/O operations
          tps --- whether to use Thin Plate Spline GCP transformer
          rpc --- whether to use RPC transformer
          geoloc --- whether to use GeoLocation array transformer
          polynomialOrder --- order of polynomial GCP interpolation
          transformerOptions --- list of transformer options
          cutlineDSName --- cutline dataset name
          cutlineLayer --- cutline layer name
          cutlineWhere --- cutline WHERE clause
          cutlineSQL --- cutline SQL statement
          cutlineBlend --- cutline blend distance in pixels
          cropToCutline --- whether to use cutline extent for output bounds
          copyMetadata --- whether to copy source metadata
          metadataConflictValue --- metadata data conflict value
          setColorInterpretation --- whether to force color interpretation of input bands to output bands
          callback --- callback method
          callback_data --- user data for callback
    """

    new_options = options
99
    # new_options += ['-of', format]
100
    if outputType != gdal.GDT_Unknown:
101
        new_options += ['-ot', gdal.GetDataTypeName(outputType)]
102
    if workingType != gdal.GDT_Unknown:
103
        new_options += ['-wt', gdal.GetDataTypeName(workingType)]
104
    if outputBounds is not None:
105
        new_options += ['-te', str(outputBounds[0]), str(outputBounds[1]), str(outputBounds[2]), str(outputBounds[3])]
106
    if outputBoundsSRS is not None:
107
        new_options += ['-te_srs', str(outputBoundsSRS)]
108
    if xRes is not None and yRes is not None:
109
        new_options += ['-tr', str(xRes), str(yRes)]
110
111
112
    if width or height:
        new_options += ['-ts', str(width), str(height)]
    if srcSRS is not None:
113
        new_options += ['-s_srs', str(srcSRS)]
114
    if dstSRS is not None:
115
        new_options += ['-t_srs', str(dstSRS)]
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
    if targetAlignedPixels:
        new_options += ['-tap']
    if srcAlpha:
        new_options += ['-srcalpha']
    if dstAlpha:
        new_options += ['-dstalpha']
    if warpOptions is not None:
        for opt in warpOptions:
            new_options += ['-wo', str(opt)]
    if errorThreshold is not None:
        new_options += ['-et', str(errorThreshold)]
    if resampleAlg is not None:
        if resampleAlg == gdal.GRA_NearestNeighbour:
            new_options += ['-r', 'near']
        elif resampleAlg == gdal.GRA_Bilinear:
            new_options += ['-rb']
        elif resampleAlg == gdal.GRA_Cubic:
            new_options += ['-rc']
        elif resampleAlg == gdal.GRA_CubicSpline:
            new_options += ['-rcs']
        elif resampleAlg == gdal.GRA_Lanczos:
            new_options += ['-r', 'lanczos']
        elif resampleAlg == gdal.GRA_Average:
            new_options += ['-r', 'average']
        elif resampleAlg == gdal.GRA_Mode:
            new_options += ['-r', 'mode']
142
143
        else:  # gdal.GRA_Gauss is missing
            new_options += ['-r', str(resampleAlg)]
144
    if warpMemoryLimit is not None:
145
        new_options += ['-wm', str(warpMemoryLimit)]
146
147
    if creationOptions is not None:
        for opt in creationOptions:
148
            new_options += ['-co', opt]
149
    if srcNodata is not None:
150
        new_options += ['-srcnodata', str(srcNodata)]
151
    if dstNodata is not None:
152
        new_options += ['-dstnodata', str(dstNodata)]
153
154
155
156
157
158
159
160
161
162
163
164
    if multithread:
        new_options += ['-multi']
    if tps:
        new_options += ['-tps']
    if rpc:
        new_options += ['-rpc']
    if geoloc:
        new_options += ['-geoloc']
    if polynomialOrder is not None:
        new_options += ['-order', str(polynomialOrder)]
    if transformerOptions is not None:
        for opt in transformerOptions:
165
            new_options += ['-to', opt]
166
    if cutlineDSName is not None:
167
        new_options += ['-cutline', str(cutlineDSName)]
168
    if cutlineLayer is not None:
169
        new_options += ['-cl', str(cutlineLayer)]
170
    if cutlineWhere is not None:
171
        new_options += ['-cwhere', str(cutlineWhere)]
172
    if cutlineSQL is not None:
173
        new_options += ['-csql', str(cutlineSQL)]
174
    if cutlineBlend is not None:
175
        new_options += ['-cblend', str(cutlineBlend)]
176
177
178
179
180
    if cropToCutline:
        new_options += ['-crop_to_cutline']
    if not copyMetadata:
        new_options += ['-nomd']
    if metadataConflictValue:
181
        new_options += ['-cvmd', str(metadataConflictValue)]
182
183
184
185
186
187
188
    if setColorInterpretation:
        new_options += ['-setci']

    if isinstance(srcDSOrSrcDSTab, gdal.Dataset):
        drv = gdal.GetDriverByName('ENVI')
        inPath = get_tempfile(prefix='warp_in_', ext='.bsq')
        drv.CreateCopy(inPath, srcDSOrSrcDSTab)
189
190
        del srcDSOrSrcDSTab
    elif isinstance(srcDSOrSrcDSTab, str):
191
192
193
194
195
196
        inPath = srcDSOrSrcDSTab
    else:
        raise ValueError

    warpedPath = get_tempfile(prefix='warp_out_', ext='.bsq')
    out, exitcode, err = subcall_with_output('gdalwarp %s %s -of ENVI -overwrite %s'
197
                                             % (inPath, warpedPath, ' '.join(new_options)))
198
199
200
201
202
203
204
205
206
207
208
    if exitcode:
        raise Exception(err)

    ds = gdal.Open(warpedPath)
    if ds is None:
        raise Exception(gdal.GetLastErrorMsg())

    drv = gdal.GetDriverByName('MEM')
    mem_ds = drv.CreateCopy(warpedPath, ds)

    # cleanup
209
210
    del ds
    [gdal.Unlink(p) for p in [inPath, os.path.splitext(inPath)[0] + '.hdr']]
211
212
213
214
215
    [gdal.Unlink(p) for p in [warpedPath, os.path.splitext(warpedPath)[0] + '.hdr']]

    return mem_ds


216
217
218
219
220
221
222
223
224
225
226
def Translate(destNameOrDestDS, srcDSOrSrcDSTab, options='', format='GTiff',
              outputType=gdal.GDT_Unknown, bandList=None, maskBand=None,
              width=0, height=0, widthPct=0.0, heightPct=0.0,
              xRes=0.0, yRes=0.0,
              creationOptions=None, srcWin=None, projWin=None, projWinSRS=None, strict=False,
              unscale=False, scaleParams=None, exponents=None,
              outputBounds=None, metadataOptions=None,
              outputSRS=None, GCPs=None,
              noData=None, rgbExpand=None,
              stats=False, rat=True, resampleAlg=None,
              callback=None, callback_data=None):
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
    """ This functions brings functionality of gdal.Translate() that is not available in GDAL versions below 2.1 (?).

        Keyword arguments are :
          options --- can be be an array of strings, a string or let empty and filled from other keywords.
          format --- output format ("GTiff", etc...)
          outputType --- output type (gdal.GDT_Byte, etc...)
          bandList --- array of band numbers (index start at 1)
          maskBand --- mask band to generate or not ("none", "auto", "mask", 1, ...)
          width --- width of the output raster in pixel
          height --- height of the output raster in pixel
          widthPct --- width of the output raster in percentage (100 = original width)
          heightPct --- height of the output raster in percentage (100 = original height)
          xRes --- output horizontal resolution
          yRes --- output vertical resolution
          creationOptions --- list of creation options
          srcWin --- subwindow in pixels to extract: [left_x, top_y, width, height]
          projWin --- subwindow in projected coordinates to extract: [ulx, uly, lrx, lry]
          projWinSRS --- SRS in which projWin is expressed
          strict --- strict mode
          unscale --- unscale values with scale and offset metadata
247
248
          scaleParams --- list of scale parameters, each of the form
                          [src_min,src_max] or [src_min,src_max,dst_min,dst_max]
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
          exponents --- list of exponentiation parameters
          outputBounds --- assigned output bounds: [ulx, uly, lrx, lry]
          metadataOptions --- list of metadata options
          outputSRS --- assigned output SRS
          GCPs --- list of GCPs
          noData --- nodata value (or "none" to unset it)
          rgbExpand --- Color palette expansion mode: "gray", "rgb", "rgba"
          stats --- whether to calculate statistics
          rat --- whether to write source RAT
          resampleAlg --- resampling mode
          callback --- callback method
          callback_data --- user data for callback
    """

    new_options = options
    new_options += ['-of', format]
    if outputType != gdal.GDT_Unknown:
266
        new_options += ['-ot', gdal.GetDataTypeName(outputType)]
267
    if maskBand is not None:
268
        new_options += ['-mask', str(maskBand)]
269
270
    if bandList is not None:
        for b in bandList:
271
            new_options += ['-b', str(b)]
272
273
274
275
276
277
    if width != 0 or height != 0:
        new_options += ['-outsize', str(width), str(height)]
    elif widthPct != 0 and heightPct != 0:
        new_options += ['-outsize', str(widthPct) + '%%', str(heightPct) + '%%']
    if creationOptions is not None:
        for opt in creationOptions:
278
            new_options += ['-co', opt]
279
280
281
282
283
284
285
286
287
288
    if srcWin is not None:
        new_options += ['-srcwin', str(srcWin[0]), str(srcWin[1]), str(srcWin[2]), str(srcWin[3])]
    if strict:
        new_options += ['-strict']
    if unscale:
        new_options += ['-unscale']
    if scaleParams:
        for scaleParam in scaleParams:
            new_options += ['-scale']
            for v in scaleParam:
289
                new_options += [str(v)]
290
291
292
293
    if exponents:
        for exponent in exponents:
            new_options += ['-exponent', str(exponent)]
    if outputBounds is not None:
294
295
        new_options += ['-a_ullr', str(outputBounds[0]), str(outputBounds[1]), str(outputBounds[2]),
                        str(outputBounds[3])]
296
297
    if metadataOptions is not None:
        for opt in metadataOptions:
298
            new_options += ['-mo', opt]
299
    if outputSRS is not None:
300
        new_options += ['-a_srs', str(outputSRS)]
301
302
    if GCPs is not None:
        for gcp in GCPs:
303
            new_options += ['-gcp', str(gcp.GCPPixel), str(gcp.GCPLine), str(gcp.GCPX), str(gcp.GCPY), str(gcp.GCPZ)]
304
305
306
    if projWin is not None:
        new_options += ['-projwin', str(projWin[0]), str(projWin[1]), str(projWin[2]), str(projWin[3])]
    if projWinSRS is not None:
307
        new_options += ['-projwin_srs', str(projWinSRS)]
308
    if noData is not None:
309
        new_options += ['-a_nodata', str(noData)]
310
    if rgbExpand is not None:
311
        new_options += ['-expand', str(rgbExpand)]
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
    if stats:
        new_options += ['-stats']
    if not rat:
        new_options += ['-norat']
    if resampleAlg is not None:
        if resampleAlg == gdal.GRA_NearestNeighbour:
            new_options += ['-r', 'near']
        elif resampleAlg == gdal.GRA_Bilinear:
            new_options += ['-r', 'bilinear']
        elif resampleAlg == gdal.GRA_Cubic:
            new_options += ['-r', 'cubic']
        elif resampleAlg == gdal.GRA_CubicSpline:
            new_options += ['-r', 'cubicspline']
        elif resampleAlg == gdal.GRA_Lanczos:
            new_options += ['-r', 'lanczos']
        elif resampleAlg == gdal.GRA_Average:
            new_options += ['-r', 'average']
        elif resampleAlg == gdal.GRA_Mode:
            new_options += ['-r', 'mode']
        else:
332
            new_options += ['-r', str(resampleAlg)]
333
    if xRes != 0 and yRes != 0:
334
        new_options += ['-tr', str(xRes), str(yRes)]
335
336
337
338
339

    if isinstance(srcDSOrSrcDSTab, gdal.Dataset):
        drv = gdal.GetDriverByName('ENVI')
        inPath = get_tempfile(prefix='translate_in_', ext='.bsq')
        drv.CreateCopy(inPath, srcDSOrSrcDSTab)
340
341
        del srcDSOrSrcDSTab
    elif isinstance(srcDSOrSrcDSTab, str):
342
343
344
345
346
347
        inPath = srcDSOrSrcDSTab
    else:
        raise ValueError

    translatedPath = get_tempfile(prefix='translate_out_', ext='.bsq')
    out, exitcode, err = subcall_with_output('gdal_translate %s %s -of ENVI %s'
348
                                             % (inPath, translatedPath, ' '.join(new_options)))
349
350
351
352
353
354
355
356
357
358
359
    if exitcode:
        raise Exception(err)

    ds = gdal.Open(translatedPath)
    if ds is None:
        raise Exception(gdal.GetLastErrorMsg())

    drv = gdal.GetDriverByName('MEM')
    mem_ds = drv.CreateCopy(translatedPath, ds)

    # cleanup
360
361
    del ds
    [gdal.Unlink(p) for p in [inPath, os.path.splitext(inPath)[0] + '.hdr']]
362
363
364
365
366
367
368
369
370
371
372
    [gdal.Unlink(p) for p in [translatedPath, os.path.splitext(translatedPath)[0] + '.hdr']]

    return mem_ds


def ensure_GDAL_version_compatibility(func2run, funcName2ensure):
    import functools
    try:
        getattr(gdal, funcName2ensure)
    except AttributeError:
        if funcName2ensure in globals():
373
            setattr(gdal, funcName2ensure, globals()[funcName2ensure])
374
        else:
375
            raise AttributeError("'gdal' has no attribute '%s'." % funcName2ensure)
376
377
378
379
380
381
382
383

    @functools.wraps(func2run)
    def inner(*args, **kwargs):
        return func2run(*args, **kwargs)

    return inner


384
def ensure_GDAL_version_compatibility_deco(funcName2ensure):
385
386
387
388
389
390
391
392
    try:
        getattr(gdal, funcName2ensure)
        funcIsMissing = False
    except AttributeError:
        funcIsMissing = True
        print('drin1')
        if funcName2ensure in globals():
            print('drin2')
393
            setattr(gdal, funcName2ensure, globals()[funcName2ensure])
394
395
396
397
            print('pre', globals()[funcName2ensure])
            gdal.Warp = globals()[funcName2ensure]
            from gdal import Warp
            print('pre2', Warp)
398
            # print(importlib.import_module('gdal.%s' % funcName2ensure))
399
        else:
400
            raise AttributeError("'gdal' has no attribute '%s'." % funcName2ensure)
401
402
403
404
405
406

    def real_decorator(function):
        def wrapper(*args, **kwargs):
            return function(*args, **kwargs)

        return wrapper
407

408
    if funcIsMissing:
409
        delattr(gdal, funcName2ensure)
410
411
412
413
414
415

    return real_decorator


def get_gdal_func(funcName):
    try:
416
        return getattr(gdal, funcName)
417
418
419
420
    except AttributeError:
        if funcName in globals():
            return globals()[funcName]
        else:
421
            raise AttributeError("'gdal' has no attribute '%s'." % funcName)