CoReg.py 83.5 KB
Newer Older
1
2
# -*- coding: utf-8 -*-

3
4
# AROSICS - Automated and Robust Open-Source Image Co-Registration Software
#
5
6
7
8
# Copyright (C) 2017-2021
# - Daniel Scheffler (GFZ Potsdam, daniel.scheffler@gfz-potsdam.de)
# - Helmholtz Centre Potsdam - GFZ German Research Centre for Geosciences Potsdam,
#   Germany (https://www.gfz-potsdam.de/)
9
10
11
12
13
#
# 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).
#
14
15
16
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
17
#
18
#   http://www.apache.org/licenses/LICENSE-2.0
19
#
20
21
22
23
24
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
25

26
27
28
import os
import time
import warnings
29
from copy import copy
30
from typing import Iterable, Union, Tuple, List, Optional  # noqa F401
31
32

# custom
33
from osgeo import gdal
34
import numpy as np
35

36
37
38
try:
    import pyfftw
except ImportError:
39
    pyfftw = None
40
from shapely.geometry import Point, Polygon
41
42

# internal modules
43
from .DeShifter import DESHIFTER, _dict_rspAlg_rsp_Int
44
45
from . import geometry as GEO
from . import plotting as PLT
46

47
from geoarray import GeoArray
48
from py_tools_ds.convenience.object_oriented import alias_property
49
from py_tools_ds.geo.coord_calc import get_corner_coordinates
50
from py_tools_ds.geo.vector.topology import get_overlap_polygon, get_smallest_boxImYX_that_contains_boxMapYX
51
from py_tools_ds.geo.projection import prj_equal
52
from py_tools_ds.geo.vector.geometry import boxObj, round_shapelyPoly_coords
53
from py_tools_ds.geo.coord_grid import move_shapelyPoly_to_image_grid, is_coord_grid_equal
54
from py_tools_ds.geo.coord_trafo import reproject_shapelyGeometry, mapXY2imXY, imXY2mapXY
55
56
from py_tools_ds.geo.raster.reproject import warp_ndarray
from py_tools_ds.geo.map_info import geotransform2mapinfo
57
from py_tools_ds.io.vector.writer import write_shp
58

59
__author__ = 'Daniel Scheffler'
60
61


62
class GeoArray_CoReg(GeoArray):
63
64
65
66
    def __init__(self,
                 CoReg_params: dict,
                 imID: str
                 ) -> None:
67
        assert imID in ['ref', 'shift']
Daniel Scheffler's avatar
CoReg:    
Daniel Scheffler committed
68

69
70
        # run GeoArray init
        path_or_geoArr = CoReg_params['im_ref'] if imID == 'ref' else CoReg_params['im_tgt']
71
72
73
        nodata = CoReg_params['nodata'][0 if imID == 'ref' else 1]
        progress = CoReg_params['progress']
        q = CoReg_params['q'] if not CoReg_params['v'] else False
74

75
        super(GeoArray_CoReg, self).__init__(path_or_geoArr, nodata=nodata, progress=progress, q=q)
76

77
        self.imID = imID
78
        self.imName = 'reference image' if imID == 'ref' else 'image to be shifted'
79
        self.v = CoReg_params['v']
80
81

        assert isinstance(self, GeoArray), \
82
            'Something went wrong with the creation of GeoArray instance for the %s. The created ' \
83
            'instance does not seem to belong to the GeoArray class. If you are working in Jupyter Notebook, reset ' \
84
            'the kernel and try again.' % self.imName
85

86
        # set title to be used in plots
87
        self.title = os.path.basename(self.filePath) if self.filePath else self.imName
88
89

        # validate params
90
91
        # assert self.prj, 'The %s has no projection.' % self.imName # TODO
        # assert not re.search('LOCAL_CS', self.prj), 'The %s is not georeferenced.' % self.imName # TODO
92
93
94
        assert self.gt, 'The %s has no map information.' % self.imName

        # set band4match
95
96
97
98
99
        self.band4match = (CoReg_params['r_b4match'] if imID == 'ref' else CoReg_params['s_b4match']) - 1
        assert self.bands >= self.band4match + 1 >= 1, \
            "The %s has %s %s. So its band number to match must be %s%s. Got %s." \
            % (self.imName, self.bands, 'bands' if self.bands > 1 else
               'band', 'between 1 and ' if self.bands > 1 else '', self.bands, self.band4match)
100

101
102
        # set footprint_poly
        given_footprint_poly = CoReg_params['footprint_poly_%s' % ('ref' if imID == 'ref' else 'tgt')]
103
        given_corner_coord = CoReg_params['data_corners_%s' % ('ref' if imID == 'ref' else 'tgt')]
104
105

        if given_footprint_poly:
106
            self.footprint_poly = given_footprint_poly
107
        elif given_corner_coord is not None:
108
            self.footprint_poly = Polygon(given_corner_coord)
109
110
        elif not CoReg_params['calc_corners']:
            # use the image extent
111
            self.footprint_poly = Polygon(get_corner_coordinates(gt=self.gt, cols=self.cols, rows=self.rows))
112
        else:
113
114
            # footprint_poly is calculated automatically by GeoArray
            if not CoReg_params['q']:
115
                print('Calculating footprint polygon and actual data corner coordinates for %s...' % self.imName)
116

117
            self.calc_mask_nodata(fromBand=self.band4match)  # this avoids that all bands have to be read
118

119
120
121
122
123
124
125
126
            with warnings.catch_warnings(record=True) as w:
                _ = self.footprint_poly  # execute getter

            if len(w) > 0 and 'disjunct polygone(s) outside' in str(w[-1].message):
                warnings.warn('The footprint of the %s contains multiple separate image parts. '
                              'AROSICS will only process the largest image part.' % self.imName)
                # FIXME use a convex hull as footprint poly

127
128
129
130
        # validate footprint poly
        if not self.footprint_poly.is_valid:
            self.footprint_poly = self.footprint_poly.buffer(0)

131
        if not self.q:
Daniel Scheffler's avatar
Daniel Scheffler committed
132
            print('Bounding box of calculated footprint for %s:\n\t%s' % (self.imName, self.footprint_poly.bounds))
133

134
135
136
        # add bad data mask
        given_mask = CoReg_params['mask_baddata_%s' % ('ref' if imID == 'ref' else 'tgt')]
        if given_mask:
137
            self.mask_baddata = given_mask  # runs GeoArray.mask_baddata.setter -> sets it to BadDataMask()
Daniel Scheffler's avatar
Daniel Scheffler committed
138

139
    poly = alias_property('footprint_poly')  # ensures that self.poly is updated if self.footprint_poly is updated
Daniel Scheffler's avatar
Daniel Scheffler committed
140
141


142
class COREG(object):
143
    """The COREG class detects and corrects global X/Y shifts between a target and reference image.
Daniel Scheffler's avatar
Daniel Scheffler committed
144
145
146
147
148
149

    Geometric shifts are calculated at a specific (adjustable) image position. Correction performs a global shifting
    in X- or Y direction.

    See help(COREG) for documentation!
    """
150

151
152
153
154
155
156
157
158
    def __init__(self,
                 im_ref: Union[GeoArray, str],
                 im_tgt: Union[GeoArray, str],
                 path_out: str = None,
                 fmt_out: str = 'ENVI',
                 out_crea_options: list = None,
                 r_b4match: int = 1,
                 s_b4match: int = 1,
Daniel Scheffler's avatar
Daniel Scheffler committed
159
                 wp: Tuple[float, float] = (None, None),
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
                 ws: Tuple[int, int] = (256, 256),
                 max_iter: int = 5,
                 max_shift: int = 5,
                 align_grids: bool = False,
                 match_gsd: bool = False,
                 out_gsd: Tuple[float] = None,
                 target_xyGrid: List[List] = None,
                 resamp_alg_deshift: str = 'cubic',
                 resamp_alg_calc: str = 'cubic',
                 footprint_poly_ref: str = None,
                 footprint_poly_tgt: str = None,
                 data_corners_ref: list = None,
                 data_corners_tgt: list = None,
                 nodata: Tuple = (None, None),
                 calc_corners: bool = True,
                 binary_ws: bool = True,
                 mask_baddata_ref: Union[GeoArray, str] = None,
                 mask_baddata_tgt: Union[GeoArray, str] = None,
                 CPUs: int = None,
                 force_quadratic_win: bool = True,
                 progress: bool = True,
                 v: bool = False,
                 path_verbose_out: str = None,
                 q: bool = False,
                 ignore_errors: bool = False
                 ) -> None:
Daniel Scheffler's avatar
Daniel Scheffler committed
186
        """Get an instance of the COREG class.
187

188
        :param im_ref:
189
190
            source path or GeoArray instance of reference image
            (any GDAL compatible image format is supported)
191
192

        :param im_tgt:
193
194
            source path or GeoArray instance of the target image, i.e., the image to be shifted
            (any GDAL compatible image format is supported)
195
196
197
198
199
200
201
202

        :param path_out:
            target path of the coregistered image
            - if None (default), the method correct_shifts() does not write to disk
            - if 'auto': /dir/of/im1/<im1>__shifted_to__<im0>.bsq

        :param fmt_out:
            raster file format for output file. ignored if path_out is None. can be any GDAL compatible raster file
203
204
            format (e.g. 'ENVI', 'GTIFF'; default: ENVI). Refer to https://gdal.org/drivers/raster/index.html to get a
            full list of supported formats.
205
206
207
208
209
210
211
212
213
214
215

        :param out_crea_options:
          GDAL creation options for the output image, e.g. ["QUALITY=80", "REVERSIBLE=YES", "WRITE_METADATA=YES"]

        :param r_b4match:
            band of reference image to be used for matching (starts with 1; default: 1)

        :param s_b4match:
            band of shift image to be used for matching (starts with 1; default: 1)

        :param wp:
216
            custom matching window position as (X, Y) map coordinate in the same projection like the reference image
217
218
219
            (default: central position of image overlap)

        :param ws:
220
            custom matching window size [pixels] as (X, Y) tuple (default: (256,256))
221
222
223
224
225
226
227
228

        :param max_iter:
            maximum number of iterations for matching (default: 5)

        :param max_shift:
            maximum shift distance in reference image pixel units (default: 5 px)

        :param align_grids:
229
230
231
232
233
234
235
            True: align the input coordinate grid to the reference (does not affect the output pixel size as long as
            input and output pixel sizes are compatible (5:30 or 10:30 but not 4:30), default = False

            - NOTE: If this is set to False, the mis-registration in the target image is corrected by updating its
              geocoding information only, i.e., without performing any resampling which preserves the original
              image values (except that a resampling is needed due to other reasons, e.g., if 'match_gsd',
              'out_gsd' or 'target_xyGrid' are given).
236
237

        :param match_gsd:
238
239
            True: match the input pixel size to the reference pixel size,
            default = False
240
241

        :param out_gsd:
242
243
            output pixel size (X/Y) in units of the reference coordinate system (default = pixel size of the target
            image), given values are overridden by match_gsd=True
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260

        :param target_xyGrid:
            a list with a target x-grid and a target y-grid like [[15,45], [15,45]]
            This overrides 'out_gsd', 'align_grids' and 'match_gsd'.

        :param resamp_alg_deshift:
            the resampling algorithm to be used for shift correction (if neccessary)
            - valid algorithms: nearest, bilinear, cubic, cubic_spline, lanczos, average, mode, max, min, med, q1, q3
            - default: cubic

        :param resamp_alg_calc:
            the resampling algorithm to be used for all warping processes during calculatio of spatial shift
            - valid algorithms: nearest, bilinear, cubic, cubic_spline, lanczos, average, mode, max, min, med, q1, q3
            - default: cubic (highly recommended)

        :param footprint_poly_ref:
            footprint polygon of the reference image (WKT string or shapely.geometry.Polygon),
261
            e.g. 'POLYGON ((299999 6000000, 299999 5890200, 409799 5890200, 409799 6000000, 299999 6000000))'
262
263
264
265
266
267
268
269
270
271
272
273

        :param footprint_poly_tgt:
            footprint polygon of the image to be shifted (WKT string or shapely.geometry.Polygon)
            e.g. 'POLYGON ((299999 6000000, 299999 5890200, 409799 5890200, 409799 6000000, 299999 6000000))'

        :param data_corners_ref:
            map coordinates of data corners within reference image. ignored if footprint_poly_ref is given.

        :param data_corners_tgt:
            map coordinates of data corners within image to be shifted. ignored if footprint_poly_tgt is given.

        :param nodata:
274
275
            no-data values for reference image and image to be shifted. The default is (None, None) which indicates
            that there is no specific no-data value for both of the input images.
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317

        :param calc_corners:
             calculate true positions of the dataset corners in order to get a useful matching window position within
             the actual image overlap (default: 1; deactivated if '-cor0' and '-cor1' are given

        :param binary_ws:
            use binary X/Y dimensions for the matching window (default: 1)

        :param mask_baddata_ref:
            path to a 2D boolean mask file (or an instance of GeoArray) for the reference image where all bad data
            pixels (e.g. clouds) are marked with True and the remaining pixels with False. Must have the same
            geographic extent and projection like 'im_ref'. The mask is used to check if the chosen matching window
            position is valid in the sense of useful data. Otherwise this window position is rejected.

        :param mask_baddata_tgt:
            path to a 2D boolean mask file (or an instance of GeoArray) for the image to be shifted where all bad data
            pixels (e.g. clouds) are marked with True and the remaining pixels with False. Must have the same
            geographic extent and projection like 'im_ref'. The mask is used to check if the chosen matching window
            position is valid in the sense of useful data. Otherwise this window position is rejected.

        :param CPUs:
            number of CPUs to use during pixel grid equalization (default: None, which means 'all CPUs available')

        :param force_quadratic_win:
            force a quadratic matching window (default: 1)

        :param progress:
            show progress bars (default: True)

        :param v:
            verbose mode (default: False)

        :param path_verbose_out:
            an optional output directory for intermediate results
            (if not given, no intermediate results are written to disk)

        :param q:
            quiet mode (default: False)

        :param ignore_errors:
            Useful for batch processing. (default: False)
            In case of error COREG.success == False and COREG.x_shift_px/COREG.y_shift_px is None
318
        """
319
        self.params = dict([x for x in locals().items() if x[0] != "self"])
320

321
322
323
324
        # input validation
        if gdal.GetDriverByName(fmt_out) is None:
            raise ValueError(fmt_out, "'%s' is not a supported GDAL driver." % fmt_out)

325
326
        if match_gsd and out_gsd:
            warnings.warn("'-out_gsd' is ignored because '-match_gsd' is set.\n")
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344

        if out_gsd and (not isinstance(out_gsd, list) or len(out_gsd) != 2):
            raise ValueError(out_gsd, 'out_gsd must be a list with two values.')

        if data_corners_ref and not isinstance(data_corners_ref[0], list):
            # group if not [[x,y],[x,y]..] but [x,y,x,y,]
            data_corners_ref = [data_corners_ref[i:i + 2]
                                for i in range(0, len(data_corners_ref), 2)]

        if data_corners_tgt and not isinstance(data_corners_tgt[0], list):
            # group if not [[x,y],[x,y]..]
            data_corners_tgt = [data_corners_tgt[i:i + 2]
                                for i in range(0, len(data_corners_tgt), 2)]

        if nodata and (not isinstance(nodata, Iterable) or len(nodata) != 2):
            raise ValueError(nodata, "'nodata' must be an iterable with two values. "
                                     "Got %s with length %s." % (type(nodata), len(nodata)))

345
        for rspAlg in [resamp_alg_deshift, resamp_alg_calc]:
346
347
348
            if rspAlg not in _dict_rspAlg_rsp_Int.keys():
                raise ValueError("'%s' is not a supported resampling algorithm." % rspAlg)

349
        if resamp_alg_calc in ['average', 5] and (v or not q):
350
            warnings.warn("The resampling algorithm 'average' causes sinus-shaped patterns in fft images that will "
351
352
                          "affect the precision of the calculated spatial shifts! It is highly recommended to "
                          "choose another resampling algorithm.")
353

354
355
356
357
358
359
360
361
362
363
364
365
        self.path_out = path_out  # updated by self.set_outpathes
        self.fmt_out = fmt_out
        self.out_creaOpt = out_crea_options
        self.win_pos_XY = wp  # updated by self.get_opt_winpos_winsize()
        self.win_size_XY = ws  # updated by self.get_opt_winpos_winsize()
        self.max_iter = max_iter
        self.max_shift = max_shift
        self.align_grids = align_grids
        self.match_gsd = match_gsd
        self.out_gsd = out_gsd
        self.target_xyGrid = target_xyGrid
        self.rspAlg_DS = resamp_alg_deshift \
366
            if isinstance(resamp_alg_deshift, str) else _dict_rspAlg_rsp_Int[resamp_alg_deshift]
367
        self.rspAlg_calc = resamp_alg_calc \
368
            if isinstance(resamp_alg_calc, str) else _dict_rspAlg_rsp_Int[resamp_alg_calc]
369
370
371
        self.calc_corners = calc_corners
        self.CPUs = CPUs
        self.bin_ws = binary_ws
372
        self.force_quadratic_win = force_quadratic_win
373
374
375
376
377
378
379
        self.v = v
        self.path_verbose_out = path_verbose_out
        self.q = q if not v else False  # overridden by v
        self.progress = progress if not q else False  # overridden by q

        self.ignErr = ignore_errors
        self.max_win_sz_changes = 3  # TODO: änderung der window size, falls nach max_iter kein valider match gefunden
380
381
382
383
384
385
        self.ref: Optional[GeoArray_CoReg] = None  # set by self.get_image_params
        self.shift: Optional[GeoArray_CoReg] = None  # set by self.get_image_params
        self.matchBox: Optional[boxObj] = None  # set by self.get_clip_window_properties()
        self.otherBox: Optional[boxObj] = None  # set by self.get_clip_window_properties()
        self.matchWin: Optional[GeoArray] = None  # set by self._get_image_windows_to_match()
        self.otherWin: Optional[GeoArray] = None  # set by self._get_image_windows_to_match()
386
387
388
        self.overlap_poly = None  # set by self._get_overlap_properties()
        self.overlap_percentage = None  # set by self._get_overlap_properties()
        self.overlap_area = None  # set by self._get_overlap_properties()
389
390
        self.imfft_xgsd = None  # set by self.get_clip_window_properties()
        self.imfft_ygsd = None  # set by self.get_clip_window_properties()
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
        self.fftw_works = None  # set by self._calc_shifted_cross_power_spectrum()
        self.fftw_win_size_YX = None  # set by calc_shifted_cross_power_spectrum()

        self.x_shift_px = None  # always in shift image units (image coords) # set by calculate_spatial_shifts()
        self.y_shift_px = None  # always in shift image units (image coords) # set by calculate_spatial_shifts()
        self.x_shift_map = None  # set by self.get_updated_map_info()
        self.y_shift_map = None  # set by self.get_updated_map_info()
        self.vec_length_map = None
        self.vec_angle_deg = None
        self.updated_map_info = None  # set by self.get_updated_map_info()
        self.ssim_orig = None  # set by self._validate_ssim_improvement()
        self.ssim_deshifted = None  # set by self._validate_ssim_improvement()
        self._ssim_improved = None  # private attribute to be filled by self.ssim_improved
        self.shift_reliability = None  # set by self.calculate_spatial_shifts()

        self.tracked_errors = []  # expanded each time an error occurs
        self.success = None  # default
        self.deshift_results = None  # set by self.correct_shifts()
409

410
        # try:
411
        gdal.AllRegister()
412
        self._check_and_handle_metaRotation()
413
414
        self._get_image_params()
        self._set_outpathes(im_ref, im_tgt)
415
        self.grid2use = 'ref' if self.shift.xgsd <= self.ref.xgsd else 'shift'
416
417
        if self.v:
            print('resolutions: ', self.ref.xgsd, self.shift.xgsd)
418

419
        self._get_overlap_properties()
420
421

        if self.v and self.path_verbose_out:
422
423
424
            write_shp(os.path.join(self.path_verbose_out, 'poly_imref.shp'), self.ref.poly, self.ref.prj)
            write_shp(os.path.join(self.path_verbose_out, 'poly_im2shift.shp'), self.shift.poly, self.shift.prj)
            write_shp(os.path.join(self.path_verbose_out, 'overlap_poly.shp'), self.overlap_poly, self.ref.prj)
425

426
427
        # FIXME: transform_mapPt1_to_mapPt2(im2shift_center_map, ds_imref.GetProjection(), ds_im2shift.GetProjection())
        # FIXME später basteln für den fall, dass projektionen nicht gleich sind
428
429
430

        # get_clip_window_properties
        self._get_opt_winpos_winsize()
431
432
433
        if not self.q:
            print('Matching window position (X,Y): %s/%s' % (self.win_pos_XY[0], self.win_pos_XY[1]))
        self._get_clip_window_properties()  # sets self.matchBox, self.otherBox and much more
434

435
        if self.v and self.path_verbose_out and self.matchBox.mapPoly and self.success is not False:
436
437
            write_shp(os.path.join(self.path_verbose_out, 'poly_matchWin.shp'),
                      self.matchBox.mapPoly, self.matchBox.prj)
438

439
        self.success = False if self.success is False or not self.matchBox.boxMapYX else None
440
441
442

        # except BaseException:

443
        self._coreg_info = None  # private attribute to be filled by self.coreg_info property
444

445
    def _handle_error(self, error, warn=False, warnMsg=None):
Daniel Scheffler's avatar
Daniel Scheffler committed
446
447
448
        """Append the given error to self.tracked_errors.

        This sets self.success to False and raises the error in case self.ignore_errors = True.
449
450
451
452
453
454
455
456
457
458
459
460
461

        :param error:   instance of an error
        :param warn:    whether to give a warning in case error would be ignored otherwise
        :param warnMsg: a custom message for the warning
        :return:
        """
        warn = warn or warnMsg is not None or self.v

        self.tracked_errors.append(error)
        self.success = False

        if self.ignErr and warn:
            warnMsg = repr(error) if not warnMsg else warnMsg
462
            print('\nWARNING: ' + warnMsg)
463
464
465
466

        if not self.ignErr:
            raise error

467
468
469
470
    def _set_outpathes(self,
                       im_ref: Union[(GeoArray, str)],
                       im_tgt: Union[(GeoArray, str)]
                       ) -> None:
471
472
473
474
475
        def get_baseN(path):
            return os.path.splitext(os.path.basename(path))[0]

        # get input paths
        def get_input_path(im):
Daniel Scheffler's avatar
Daniel Scheffler committed
476
477
478
479
480
481
482
483
            path = im.filePath if isinstance(im, GeoArray) else im

            if isinstance(im, GeoArray) and im.filePath is None and self.path_out == 'auto':
                raise ValueError(self.path_out, "The output path must be explicitly set in case the input "
                                                "reference or target image is in-memory (without a reference to a "
                                                "physical file on disk). Received path_out='%s'." % self.path_out)

            return path
484

Daniel Scheffler's avatar
Daniel Scheffler committed
485
486
        path_im_ref = get_input_path(im_ref)
        path_im_tgt = get_input_path(im_tgt)
487

488
        if self.path_out:  # this also applies to self.path_out='auto'
489
490
491
492

            if self.path_out == 'auto':
                dir_out, fName_out = os.path.dirname(path_im_tgt), ''
            else:
493
                dir_out, fName_out = os.path.split(self.path_out)
494
495
496
497
498
499
500
501
502
503
504
505
506
507

            if dir_out and fName_out:
                # a valid output path is given => do nothing
                pass

            else:
                # automatically create an output directory and filename if not given
                if not dir_out:
                    if not path_im_ref:
                        dir_out = os.path.abspath(os.path.curdir)
                    else:
                        dir_out = os.path.dirname(path_im_ref)

                if not fName_out:
508
509
510
511
512
                    ext = 'bsq' if self.fmt_out == 'ENVI' else \
                        gdal.GetDriverByName(self.fmt_out).GetMetadataItem(gdal.DMD_EXTENSION)
                    fName_out = fName_out if fName_out not in ['.', ''] else \
                        '%s__shifted_to__%s' % (get_baseN(path_im_tgt), get_baseN(path_im_ref))
                    fName_out = fName_out + '.%s' % ext if ext else fName_out
513

514
                self.path_out = os.path.abspath(os.path.join(dir_out, fName_out))
515
516
517
518

                assert ' ' not in self.path_out, \
                    "The path of the output image contains whitespaces. This is not supported by GDAL."
        else:
519
            # this only happens if COREG is not instanced from within Python and self.path_out is explicitly set to None
520
521
522
523
524
525
526
527
528
529
530
            # => DESHIFTER will return an array
            pass

        if self.v:
            if self.path_verbose_out:
                dir_out, dirname_out = os.path.split(self.path_verbose_out)

                if not dir_out:
                    if self.path_out:
                        self.path_verbose_out = os.path.dirname(self.path_out)
                    else:
531
532
533
                        self.path_verbose_out = \
                            os.path.abspath(os.path.join(os.path.curdir, 'CoReg_verboseOut__%s__shifted_to__%s'
                                                         % (get_baseN(path_im_tgt), get_baseN(path_im_ref))))
534
535
536
537
538
539
540
541
542
                elif dirname_out and not dir_out:
                    self.path_verbose_out = os.path.abspath(os.path.join(os.path.curdir, dirname_out))

                assert ' ' not in self.path_verbose_out, \
                    "'path_verbose_out' contains whitespaces. This is not supported by GDAL."

        else:
            self.path_verbose_out = None

543
544
        if self.path_verbose_out and not os.path.isdir(self.path_verbose_out):
            os.makedirs(self.path_verbose_out)
545

546
    def _get_image_params(self) -> None:
547
548
        self.ref = GeoArray_CoReg(self.params, 'ref')
        self.shift = GeoArray_CoReg(self.params, 'shift')
549
550

        if not prj_equal(self.ref.prj, self.shift.prj):
551
552
            from pyproj import CRS

553
554
555
556
557
558
            crs_ref = CRS.from_user_input(self.ref.prj)
            crs_shift = CRS.from_user_input(self.shift.prj)

            name_ref, name_shift = \
                (crs_ref.name, crs_shift.name) if not crs_ref.name == crs_shift.name else (crs_ref.srs, crs_shift.srs)

559
            raise RuntimeError(
560
                'Input projections are not equal. Different projections are currently not supported. '
561
                'Got %s vs. %s.' % (name_ref, name_shift))
562

563
    def _get_overlap_properties(self) -> None:
564
565
566
567
568
569
        with warnings.catch_warnings():
            # already warned in GeoArray_CoReg.__init__()
            warnings.filterwarnings("ignore", category=RuntimeWarning, message=".*disjunct.*")

            overlap_tmp = get_overlap_polygon(self.ref.poly, self.shift.poly, self.v)

570
571
572
        self.overlap_poly = overlap_tmp['overlap poly']  # has to be in reference projection
        self.overlap_percentage = overlap_tmp['overlap percentage']
        self.overlap_area = overlap_tmp['overlap area']
573
574
575
576

        assert self.overlap_poly, 'The input images have no spatial overlap.'

        # overlap are must at least cover 16*16 pixels
577
578
579
580
        px_area = self.ref.xgsd * self.ref.ygsd if self.grid2use == 'ref' else self.shift.xgsd * self.shift.ygsd
        px_covered = self.overlap_area / px_area
        assert px_covered > 16 * 16, \
            'Overlap area covers only %s pixels. At least 16*16 pixels are needed.' % px_covered
581

582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
    def _check_and_handle_metaRotation(self):
        """Check if the provided input data have a metadata rotation and if yes, correct it.

        In case there is a rotation, the GDAL GeoTransform is not 0 at positions 2 or 4. So far, AROSICS does not
        handle such rotations, so the resampling is needed to make things work.
        """
        gA_ref = GeoArray(self.params['im_ref'])
        gA_tgt = GeoArray(self.params['im_tgt'])

        msg = 'The %s image needs to be resampled because it has a row/column rotation in ' \
              'its map info which is not handled by AROSICS.'

        if GEO.has_metaRotation(gA_ref):
            warnings.warn(msg % 'reference')
            self.params['im_ref'] = GEO.remove_metaRotation(gA_ref)

        if GEO.has_metaRotation(gA_tgt):
            warnings.warn(msg % 'target')
            self.params['im_tgt'] = GEO.remove_metaRotation(gA_tgt)

    @property
    def are_pixGrids_equal(self):
        return prj_equal(self.ref.prj, self.shift.prj) and \
               is_coord_grid_equal(self.ref.gt, *self.shift.xygrid_specs, tolerance=1e-8)

607
    def equalize_pixGrids(self) -> None:
608
609
610
611
612
        """Equalize image grids and projections of reference and target image (align target to reference).

        NOTE: This method is only called by COREG_LOCAL to speed up processing during detection of displacements.
        """
        if not self.are_pixGrids_equal or GEO.has_metaRotation(self.ref) or GEO.has_metaRotation(self.shift):
613
614
            if not self.q:
                print("Equalizing pixel grids and projections of reference and target image...")
Daniel Scheffler's avatar
Daniel Scheffler committed
615

616
617
618
619
620
621
622
623
            def equalize(gA_from: GeoArray, gA_to: GeoArray) -> GeoArray:
                if gA_from.bands > 1:
                    gA_from = gA_from.get_subset(zslice=slice(gA_from.band4match, gA_from.band4match + 1))
                gA_from.reproject_to_new_grid(prototype=gA_to, CPUs=self.CPUs)
                gA_from.band4match = 0  # after resampling there is only one band in the GeoArray

                return gA_from

624
            if self.grid2use == 'ref':
625
626
                # resample target to reference image
                self.shift = equalize(gA_from=self.shift, gA_to=self.ref)
627

628
            else:
629
630
                # resample reference to target image
                self.ref = equalize(gA_from=self.ref, gA_to=self.shift)
631

632
633
634
            # self.ref.gt = (self.ref.gt[0], 1, self.ref.gt[2], self.ref.gt[3], self.ref.gt[4], -1)
            # self.shift.gt = (self.shift.gt[0], 1, self.shift.gt[2], self.shift.gt[3], self.shift.gt[4], -1)

635
    def show_image_footprints(self):
Daniel Scheffler's avatar
Daniel Scheffler committed
636
637
638
639
        """Show a web map containing the calculated footprints and overlap area of the input images.

        NOTE: This method is intended to be called from Jupyter Notebook.
        """
640
641
642
        # TODO different colors for polygons
        assert self.overlap_poly, 'Please calculate the overlap polygon first.'

643
644
        import folium
        import geojson
645

646
647
648
649
        refPoly = reproject_shapelyGeometry(self.ref.poly, self.ref.prj, 4326)
        shiftPoly = reproject_shapelyGeometry(self.shift.poly, self.shift.prj, 4326)
        overlapPoly = reproject_shapelyGeometry(self.overlap_poly, self.shift.prj, 4326)
        matchBoxPoly = reproject_shapelyGeometry(self.matchBox.mapPoly, self.shift.prj, 4326)
650
651

        m = folium.Map(location=tuple(np.array(overlapPoly.centroid.coords.xy).flatten())[::-1])
652
        for poly in [refPoly, shiftPoly, overlapPoly, matchBoxPoly]:
653
654
655
656
            gjs = geojson.Feature(geometry=poly, properties={})
            folium.GeoJson(gjs).add_to(m)
        return m

657
658
659
660
661
662
    def show_matchWin(self,
                      figsize: tuple = (15, 15),
                      interactive: bool = True,
                      after_correction: bool = None,
                      pmin=2,
                      pmax=98):
663
        """Show the image content within the matching window.
664

665
666
        :param figsize:             figure size
        :param interactive:         whether to return an interactive figure based on 'holoviews' library
667
668
669
670
671
        :param after_correction:    True/False: show the image content AFTER shift correction or before
                                    None: show both states - before and after correction (default)
        :param pmin:                percentage to be used for excluding the darkest pixels from stretching (default: 2)
        :param pmax:                percentage to be used for excluding the brightest pixels from stretching
                                    (default: 98)
672
673
        :return:
        """
674
675
676
677
678
        if not self.success and after_correction in [True, None]:
            warnings.warn('It is only possible to show the matching window before correction of spatial displacements '
                          'because no valid displacement has been calculated yet.')
            after_correction = False

679
680
681
682
683
        if interactive:
            # use Holoviews
            try:
                import holoviews as hv
            except ImportError:
684
                hv = None
685
686
687
            if not hv:
                raise ImportError(
                    "This method requires the library 'holoviews'. It can be installed for Anaconda with "
688
                    "the shell command 'conda install -c conda-forge holoviews bokeh'.")
689

690
            hv.notebook_extension('matplotlib')
691
692
693
694
695
696
697
            hv.Store.add_style_opts(hv.Image, ['vmin', 'vmax'])

            # hv.Store.option_setters.options().Image = hv.Options('style', cmap='gnuplot2')
            # hv.Store.add_style_opts(hv.Image, ['cmap'])
            # renderer = hv.Store.renderers['matplotlib'].instance(fig='svg', holomap='gif')
            # RasterPlot = renderer.plotting_class(hv.Image)
            # RasterPlot.cmap = 'gray'
698
            otherWin_corr = self._get_deshifted_otherWin() if after_correction in [True, None] else None
699
700
            xmin, xmax, ymin, ymax = self.matchBox.boundsMap

701
            def get_hv_image(geoArr):
702
703
                from skimage.exposure import rescale_intensity  # import here to avoid static TLS ImportError

704
705
706
707
708
                arr_masked = np.ma.masked_equal(geoArr[:], geoArr.nodata)
                vmin = np.nanpercentile(arr_masked.compressed(), pmin)
                vmax = np.nanpercentile(arr_masked.compressed(), pmax)
                arr2plot = rescale_intensity(arr_masked, in_range=(vmin, vmax), out_range='int8')

709
710
711
712
713
714
715
716
                return hv.Image(arr2plot, bounds=(xmin, ymin, xmax, ymax))\
                    .opts(style={'cmap': 'gray',
                                 'vmin': vmin,
                                 'vmax': vmax,
                                 'interpolation': 'none'},
                          plot={'fig_inches': figsize,
                                # 'fig_size': 100,
                                'show_grid': True})
717

718
719
            hvIm_matchWin = get_hv_image(self.matchWin)
            hvIm_otherWin_orig = get_hv_image(self.otherWin)
720
            hvIm_otherWin_corr = get_hv_image(otherWin_corr) if after_correction in [True, None] else None
721

722
723
724
            if after_correction is None:
                # view both states
                print('Matching window before and after correction (above and below): ')
725

726
                # get layouts (docs on options: https://holoviews.org/user_guide)
727
728
                layout_before = (hvIm_matchWin + hvIm_matchWin).opts(plot=dict(fig_inches=figsize))
                layout_after = (hvIm_otherWin_orig + hvIm_otherWin_corr).opts(plot=dict(fig_inches=figsize))
729

730
731
732
733
734
735
736
737
738
739
                # plot!
                imgs = {1: layout_before, 2: layout_after}
                hmap = hv.HoloMap(imgs, kdims=['image']).collate().cols(1)

            else:
                # view state before or after correction
                imgs = {1: hvIm_matchWin, 2: hvIm_otherWin_corr if after_correction else hvIm_otherWin_orig}
                hmap = hv.HoloMap(imgs, kdims=['image'])

            # Construct a HoloMap by evaluating the function over all the keys
740
            # hmap = hv.HoloMap(imgs_corr, kdims=['image']) +  hv.HoloMap(imgs_corr, kdims=['image'])
741

742
743
            # Construct a HoloMap by defining the sampling on the Dimension
            # dmap = hv.DynamicMap(image_slice, kdims=[hv.Dimension('z_axis', values=keys)])
744

745
            return hmap
746

747
748
        else:
            # TODO add titles
Daniel Scheffler's avatar
Daniel Scheffler committed
749
            # TODO handle after_correction=None here
750
            self.matchWin.show(figsize=figsize)
751
            if after_correction:
752
                self._get_deshifted_otherWin().show(figsize=figsize, pmin=pmin, pmax=pmax)
753
            else:
754
                self.otherWin.show(figsize=figsize, pmin=pmin, pmax=pmax)
755

756
    def show_cross_power_spectrum(self, interactive: bool = False) -> None:
Daniel Scheffler's avatar
Daniel Scheffler committed
757
758
759
760
        """Show a 3D surface of the cross power spectrum.

        NOTE: The cross power spectrum is the result from phase correlating the reference and target
              image within the matching window.
761
762
763
764
765
766
767

        :param interactive:  whether to return an interactice 3D surface plot based on 'plotly' library
        :return:
        """
        if interactive:
            # create plotly 3D surface

768
            # import plotly.plotly as py # online mode -> every plot is uploaded into online plotly account
769
770
771
772
773
774
            from plotly.offline import iplot, init_notebook_mode
            import plotly.graph_objs as go

            init_notebook_mode(connected=True)

            z_data = self._calc_shifted_cross_power_spectrum()
775
            data = [go.Surface(z=z_data)]
776
777
778
779
780
            layout = go.Layout(
                title='cross power spectrum',
                autosize=False,
                width=1000,
                height=1000,
781
                margin={'l': 65, 'r': 50, 'b': 65, 't': 90})
782
            fig = go.Figure(data=data, layout=layout)
783
784
785
786
787
788
789
790

            return iplot(fig, filename='SCPS')

        else:
            # use matplotlib
            scps = self._calc_shifted_cross_power_spectrum()
            PLT.subplot_3dsurface(scps.astype(np.float32))

791
    def _get_opt_winpos_winsize(self) -> None:
Daniel Scheffler's avatar
Daniel Scheffler committed
792
793
794
        """Calculate optimal window position and size in reference image units.

        NOTE: The returned values are computed according to DGM, cloud_mask and trueCornerLonLat.
795
        """
796
797
798
799
        # dummy algorithm: get center position of overlap instead of searching ideal window position in whole overlap
        # TODO automatischer Algorithmus zur Bestimmung der optimalen Window Position

        wp = tuple(self.win_pos_XY)
800
801
        assert type(self.win_pos_XY) in [tuple, list, np.ndarray], \
            'The window position must be a tuple of two elements. Got %s with %s elements.' % (type(wp), len(wp))
802
803
804
        wp = tuple(wp)

        if None in wp:
805
            # use centroid point if possible
806
807
808
            overlap_center_pos_x, overlap_center_pos_y = self.overlap_poly.centroid.coords.xy
            wp = (wp[0] if wp[0] else overlap_center_pos_x[0]), (wp[1] if wp[1] else overlap_center_pos_y[0])

809
            # validate window position
810
            if not self.overlap_poly.buffer(1e-5).contains(Point(wp)):
811
812
813
814
815
816
817
818
819
820
821
                # in case the centroid point is not within overlap area
                if not self.q:
                    warnings.warn("The centroid point of the two input images could not be used as matching window "
                                  "position since it is outside of the overlap area. Instead the so called "
                                  "'representative point' is used. Alternatively you can provide your own window "
                                  "position as input parameter.")

                # -> use representative point: a point that is garanteed to be within overlap polygon
                overlap_center_pos_x, overlap_center_pos_y = self.overlap_poly.representative_point().coords.xy
                wp = overlap_center_pos_x[0], overlap_center_pos_y[0]

822
            assert self.overlap_poly.buffer(1e-5).contains(Point(wp))
823
824
825

        else:
            # validate window position
826
            if not self.overlap_poly.buffer(1e-5).contains(Point(wp)):
827
                self._handle_error(ValueError('The provided window position %s/%s is outside of the overlap '
828
                                              'area of the two input images. Check the coordinates.' % wp))
829
830
831
832
833
834

        # check if window position is within bad data area if a respective mask has been provided
        for im in [self.ref, self.shift]:
            if im.mask_baddata is not None:
                imX, imY = mapXY2imXY(wp, im.mask_baddata.gt)

835
                if im.mask_baddata[int(imY), int(imX)] is True:
836
                    self._handle_error(
837
                        RuntimeError('According to the provided bad data mask for the %s the chosen window position '
838
839
840
                                     '%s / %s is within a bad data area. Using this window position for coregistration '
                                     'is not reasonable. Please provide a better window position!'
                                     % (im.imName, wp[0], wp[1])))
841

842
843
        self.win_pos_XY = wp
        self.win_size_XY = (int(self.win_size_XY[0]), int(self.win_size_XY[1])) if self.win_size_XY else (512, 512)
844

845
    def _get_clip_window_properties(self) -> None:
Daniel Scheffler's avatar
Daniel Scheffler committed
846
847
848
849
850
        """Calculate all properties of the matching window and the other window.

        These windows are used to read the corresponding image positions in the reference and the target image.

        NOTE: Even if X- and Y-dimension of the target window is equal, the output window can be NON-quadratic!
851
852
853
        """
        # FIXME image sizes like 10000*256 are still possible

854
855
        wpX, wpY = self.win_pos_XY
        wsX, wsY = self.win_size_XY
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879

        # image units -> map units
        ref_wsX = wsX * self.ref.xgsd
        ref_wsY = wsY * self.ref.ygsd
        shift_wsX = wsX * self.shift.xgsd
        shift_wsY = wsY * self.shift.ygsd

        ref_box_kwargs = \
            dict(wp=(wpX, wpY),
                 ws=(ref_wsX, ref_wsY),
                 gt=self.ref.gt)
        shift_box_kwargs = \
            dict(wp=(wpX, wpY),
                 ws=(shift_wsX, shift_wsY),
                 gt=self.shift.gt)
        matchBox =\
            boxObj(**ref_box_kwargs) if self.grid2use == 'ref' else \
            boxObj(**shift_box_kwargs)
        otherBox = \
            boxObj(**shift_box_kwargs) if self.grid2use == 'ref' else \
            boxObj(**ref_box_kwargs)
        overlapWin = \
            boxObj(mapPoly=self.overlap_poly,
                   gt=self.ref.gt)
880
881

        # clip matching window to overlap area
882
883
        matchBox.mapPoly = matchBox.mapPoly.intersection(overlapWin.mapPoly)

884
        # check if matchBox extent touches no data area of the image -> if yes: shrink it
885
886
        overlapPoly_within_matchWin = matchBox.mapPoly.intersection(self.overlap_poly)
        if overlapPoly_within_matchWin.area < matchBox.mapPoly.area:
887
888
889
890
891
892
893
            wsX_start, wsY_start = \
                1 if wsX >= wsY else \
                wsX / wsY, 1 if wsY >= wsX else \
                wsY / wsX
            box = boxObj(**dict(wp=(wpX, wpY),
                                ws=(wsX_start, wsY_start),
                                gt=matchBox.gt))
894
            while True:
895
                box.buffer_imXY(1, 1)
896
897
898
899
                if not box.mapPoly.within(overlapPoly_within_matchWin):
                    box.buffer_imXY(-1, -1)
                    matchBox = box
                    break
900
901

        # move matching window to imref grid or im2shift grid
902
903
        mW_rows, mW_cols = \
            (self.ref.rows, self.ref.cols) if self.grid2use == 'ref' else \
904
            (self.shift.rows, self.shift.cols)
905
906
907
908
        matchBox.mapPoly = move_shapelyPoly_to_image_grid(matchBox.mapPoly,
                                                          matchBox.gt, mW_rows,
                                                          mW_cols,
                                                          'NW')
909

910
        # check, if matchBox was moved outside of overlap_poly when moving it to the image grid
911
        if not matchBox.mapPoly.within(overlapWin.mapPoly):
912
            # further shrink matchPoly (1 px buffer is enough because the window was only moved to the grid)
913
            xLarger, yLarger = matchBox.is_larger_DimXY(overlapWin.boundsIm)
914
915
            matchBox.buffer_imXY(-1 if xLarger else 0,
                                 -1 if yLarger else 0)
916

917
        # matching_win directly on grid2use (fix rounding error through coordinate transformation)
918
        matchBox.imPoly = round_shapelyPoly_coords(matchBox.imPoly, precision=0)
919

920
921
922
923
924
925
926
927
928
929
930
931
932
        # check if matching window larger than the other one or equal
        if not (matchBox.mapPoly.within(otherBox.mapPoly) or
                matchBox.mapPoly == otherBox.mapPoly):
            # if yes, find the smallest 'other window' that encloses the matching window
            otherBox.boxImYX = \
                get_smallest_boxImYX_that_contains_boxMapYX(
                    matchBox.boxMapYX,
                    otherBox.gt,
                    tolerance_ndigits=5  # avoids float coordinate rounding issues
                )

        # in case after enlarging the 'other window', it gets too large for the overlap area
        # -> shrink match window and recompute smallest possible other window until everything is fine
Daniel Scheffler's avatar
Daniel Scheffler committed
933
        t_start = time.time()
934
935
        while not otherBox.mapPoly.within(overlapWin.mapPoly):
            xLarger, yLarger = otherBox.is_larger_DimXY(overlapWin.boundsIm)
936
937
            matchBox.buffer_imXY(-1 if xLarger else 0,
                                 -1 if yLarger else 0)
938
            previous_area = otherBox.mapPoly.area
939
940
941
942
943
944
945
946
947
            otherBox.boxImYX = \
                get_smallest_boxImYX_that_contains_boxMapYX(
                    matchBox.boxMapYX,
                    otherBox.gt,
                    tolerance_ndigits=5  # avoids float coordinate rounding issues
                )

            if previous_area == otherBox.mapPoly.area or \
               time.time() - t_start > 1.5:
Daniel Scheffler's avatar
Daniel Scheffler committed
948
949
                # happens e.g in case of a triangular footprint
                # NOTE: first condition is not always fulfilled -> therefore added timeout of 1.5 sec
950
                self._handle_error(
951
952
                    RuntimeError('Matching window in target image is larger than overlap area but further shrinking '
                                 'the matching window is not possible. Check if the footprints of the input data have '
953
                                 'been computed correctly.' +
954
955
                                 (' Matching window shrinking timed out.' if time.time() - t_start > 5 else '')))
                break  # break out of while loop in order to avoid that code gets stuck here
956

Daniel Scheffler's avatar
Daniel Scheffler committed
957
958
        # output validation
        for winBox in [matchBox, otherBox]:
959
960
            if winBox.imDimsYX[0] < 16 or \
               winBox.imDimsYX[1] < 16:
Daniel Scheffler's avatar
Daniel Scheffler committed
961
962
963
964
                self._handle_error(
                    RuntimeError("One of the input images does not have sufficient gray value information "
                                 "(non-no-data values) for placing a matching window at the position %s. "
                                 "Matching failed." % str((wpX, wpY))))
Daniel Scheffler's avatar
Daniel Scheffler committed
965

966
        if self.success is not False:
Daniel Scheffler's avatar
Daniel Scheffler committed
967
            # check result -> ProgrammingError if not fulfilled
968
            def within_equal(inner, outer):
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
                return inner.within(outer.buffer(1e-5)) or \
                       inner.equals(outer)

            assert within_equal(matchBox.mapPoly,
                                otherBox.mapPoly)
            assert within_equal(otherBox.mapPoly,
                                overlapWin.mapPoly)

            if self.grid2use == 'ref':
                self.imfft_xgsd = self.ref.xgsd
                self.imfft_ygsd = self.ref.ygsd
                self.ref.win = matchBox
                self.shift.win = otherBox
            else:
                self.imfft_xgsd = self.shift.xgsd
                self.imfft_ygsd = self.shift.ygsd
                self.ref.win = otherBox
                self.shift.win = matchBox
987

988
989
            self.matchBox = matchBox
            self.otherBox = otherBox
990

991
992
993
            self.ref.win.size_YX = tuple([int(i) for i in self.ref.win.imDimsYX])
            self.shift.win.size_YX = tuple([int(i) for i in self.shift.win.imDimsYX])
            match_win_size_XY = tuple(reversed([int(i) for i in matchBox.imDimsYX]))
994

995
996
            if not self.q and \
               match_win_size_XY != self.win_size_XY:
997
                print('Target window size %s not possible due to too small overlap area or window position too close '
998
                      'to an image edge. New matching window size: %s.' % (self.win_size_XY, match_win_size_XY))
999

1000
                # write_shp('matchMapPoly.shp', matchBox.mapPoly,matchBox.prj)