CoReg.py 82.3 KB
Newer Older
1
2
3
4
5
6
7
8
9
# -*- coding: utf-8 -*-
__author__='Daniel Scheffler'

import os
import re
import shutil
import subprocess
import time
import warnings
10
from copy import copy
11
12

# custom
13
14
15
16
try:
    import gdal
except ImportError:
    from osgeo import gdal
17
import numpy as np
18
19
20
try:
    import pyfftw
except ImportError:
21
    pyfftw = None
22
from shapely.geometry import Point, Polygon
23
from skimage.exposure import rescale_intensity
24

25
26
27
28
29
30
31
try:
    import geoarray
except ImportError:
    raise ImportError("Since 2017/03/31 CoReg_Sat depends on the package 'geoarray'. "
                      "You need an invitation to the respective GitLab repository from Daniel Scheffler. "
                      "Then follow the install instructions there.")

32
# internal modules
33
from .DeShifter import DESHIFTER, _dict_rspAlg_rsp_Int
34
35
36
37
from .          import geometry  as GEO
from .          import io        as IO
from .          import plotting  as PLT

38
39
40
41
42
43
44
45
from geoarray import GeoArray
from py_tools_ds.ptds.convenience.object_oriented import alias_property
from py_tools_ds.ptds.geo.coord_calc import corner_coord_to_minmax, get_corner_coordinates
from py_tools_ds.ptds.geo.vector.topology import get_overlap_polygon, get_smallest_boxImYX_that_contains_boxMapYX
from py_tools_ds.ptds.geo.projection import prj_equal, get_proj4info
from py_tools_ds.ptds.geo.vector.geometry import boxObj, round_shapelyPoly_coords
from py_tools_ds.ptds.geo.coord_grid import move_shapelyPoly_to_image_grid
from py_tools_ds.ptds.geo.coord_trafo import pixelToMapYX, reproject_shapelyGeometry, mapXY2imXY
46
from py_tools_ds.ptds.geo.raster.reproject import warp_ndarray
47
48
49
from py_tools_ds.ptds.geo.map_info import geotransform2mapinfo
from py_tools_ds.ptds.numeric.vector import find_nearest
from py_tools_ds.ptds.similarity.raster import calc_ssim
50
51
52
53




54
class GeoArray_CoReg(GeoArray):
55
    def __init__(self, CoReg_params, imID):
56
57
        # type: (dict, str) -> None

58
        assert imID in ['ref', 'shift']
Daniel Scheffler's avatar
CoReg:    
Daniel Scheffler committed
59

60
61
62
63
64
65
        # run GeoArray init
        path_or_geoArr = CoReg_params['im_ref'] if imID == 'ref' else CoReg_params['im_tgt']
        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

66
        super(GeoArray_CoReg, self).__init__(path_or_geoArr, nodata=nodata, progress=progress, q=q)
67
68

        self.imID   = imID
69
        self.imName = 'reference image' if imID == 'ref' else 'image to be shifted'
70
71
72
        self.v      = CoReg_params['v']

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

77
        # set title to be used in plots
78
        self.title = os.path.basename(self.filePath) if self.filePath else self.imName
79
80
81
82
83
84
85

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

        # set band4match
86
        self.band4match = (CoReg_params['r_b4match'] if imID == 'ref' else CoReg_params['s_b4match'])-1
87
88
89
        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)
90

91
92
93
94
95
        # set footprint_poly
        given_footprint_poly = CoReg_params['footprint_poly_%s' % ('ref' if imID == 'ref' else 'tgt')]
        given_corner_coord   = CoReg_params['data_corners_%s'   % ('ref' if imID == 'ref' else 'tgt')]

        if given_footprint_poly:
96
            self.footprint_poly = given_footprint_poly
97
        elif given_corner_coord is not None:
98
            self.footprint_poly = Polygon(given_corner_coord)
99
100
        elif not CoReg_params['calc_corners']:
            # use the image extent
101
            self.footprint_poly = Polygon(get_corner_coordinates(gt=self.gt, cols=self.cols,rows=self.rows))
102
        else:
103
104
105
            # footprint_poly is calculated automatically by GeoArray
            if not CoReg_params['q']:
                print('Calculating actual data corner coordinates for %s...' % self.imName)
106
            self.calc_mask_nodata(fromBand=self.band4match)  # this avoids that all bands have to be read
107

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

111
112
113
        # add bad data mask
        given_mask = CoReg_params['mask_baddata_%s' % ('ref' if imID == 'ref' else 'tgt')]
        if given_mask:
Daniel Scheffler's avatar
Daniel Scheffler committed
114
            self.mask_baddata = given_mask # runs GeoArray.mask_baddata.setter -> sets it to BadDataMask()
115
116


Daniel Scheffler's avatar
Daniel Scheffler committed
117
118
119
120
    poly = alias_property('footprint_poly') # ensures that self.poly is updated if self.footprint_poly is updated



121
class COREG(object):
122
123
    """See help(COREG) for documentation!"""

124
    def __init__(self, im_ref, im_tgt, path_out=None, fmt_out='ENVI', out_crea_options=None, r_b4match=1, s_b4match=1,
Daniel Scheffler's avatar
Daniel Scheffler committed
125
                 wp=(None,None), ws=(256, 256), max_iter=5, max_shift=5, align_grids=False, match_gsd=False,
126
127
                 out_gsd=None, target_xyGrid=None, resamp_alg_deshift='cubic', resamp_alg_calc='cubic',
                 footprint_poly_ref=None, footprint_poly_tgt=None, data_corners_ref=None, data_corners_tgt=None,
128
                 nodata=(None,None), calc_corners=True, binary_ws=True, mask_baddata_ref=None, mask_baddata_tgt=None,
Daniel Scheffler's avatar
Daniel Scheffler committed
129
                 CPUs=None, force_quadratic_win=True, progress=True, v=False, path_verbose_out=None, q=False,
130
                 ignore_errors=False):
131
132
133
134

        """Detects and corrects global X/Y shifts between a target and refernce image. Geometric shifts are calculated
        at a specific (adjustable) image position. Correction performs a global shifting in X- or Y direction.

135
136
137
138
        :param im_ref(str, GeoArray):   source path (any GDAL compatible image format is supported) or GeoArray instance
                                        of reference image
        :param im_tgt(str, GeoArray):   source path (any GDAL compatible image format is supported) or GeoArray instance
                                        of image to be shifted
139
        :param path_out(str):           target path of the coregistered image
140
141
142
                                            - 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(str):            raster file format for output file. ignored if path_out is None. can be any GDAL
143
144
                                        compatible raster file format (e.g. 'ENVI', 'GeoTIFF'; default: ENVI). Refer to
                                        http://www.gdal.org/formats_list.html to get a full list of supported formats.
145
146
        :param out_crea_options(list):  GDAL creation options for the output image,
                                        e.g. ["QUALITY=80", "REVERSIBLE=YES", "WRITE_METADATA=YES"]
147
148
149
150
        :param r_b4match(int):          band of reference image to be used for matching (starts with 1; default: 1)
        :param s_b4match(int):          band of shift image to be used for matching (starts with 1; default: 1)
        :param wp(tuple):               custom matching window position as map values in the same projection like the
                                        reference image (default: central position of image overlap)
Daniel Scheffler's avatar
Daniel Scheffler committed
151
        :param ws(tuple):               custom matching window size [pixels] (default: (256,256))
152
153
154
155
156
157
        :param max_iter(int):           maximum number of iterations for matching (default: 5)
        :param max_shift(int):          maximum shift distance in reference image pixel units (default: 5 px)
        :param align_grids(bool):       align the coordinate grids of the image to be and the reference image (default: 0)
        :param match_gsd(bool):         match the output pixel size to pixel size of the reference image (default: 0)
        :param out_gsd(tuple):          xgsd ygsd: set the output pixel size in map units
                                        (default: original pixel size of the image to be shifted)
158
159
        :param target_xyGrid(list):     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'.
160
161
162
163
164
165
166
167
168
        :param resamp_alg_deshift(str)  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(str)     the resampling algorithm to be used for all warping processes during calculation
                                        of spatial shifts
                                        (valid algorithms: nearest, bilinear, cubic, cubic_spline, lanczos, average, mode,
                                                       max, min, med, q1, q3)
                                        default: cubic (highly recommended)
169
170
171
172
173
174
175
176
177
178
        :param footprint_poly_ref(str): footprint polygon of the reference image (WKT string or shapely.geometry.Polygon),
                                        e.g. 'POLYGON ((299999 6000000, 299999 5890200, 409799 5890200, 409799 6000000,
                                                        299999 6000000))'
        :param footprint_poly_tgt(str): 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(list):  map coordinates of data corners within reference image.
                                        ignored if footprint_poly_ref is given.
        :param data_corners_tgt(list):  map coordinates of data corners within image to be shifted.
                                        ignored if footprint_poly_tgt is given.
179
180
181
182
183
        :param nodata(tuple):           no data values for reference image and image to be shifted
        :param calc_corners(bool):      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(bool):         use binary X/Y dimensions for the matching window (default: 1)
184
185
186
187
188
189
190
191
192
193
194
195
        :param mask_baddata_ref(str, GeoArray): 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(str, GeoArray): 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.
Daniel Scheffler's avatar
Daniel Scheffler committed
196
197
        :param CPUs(int):               number of CPUs to use during pixel grid equalization
                                        (default: None, which means 'all CPUs available')
198
        :param force_quadratic_win(bool):   force a quadratic matching window (default: 1)
199
        :param progress(bool):          show progress bars (default: True)
200
        :param v(bool):                 verbose mode (default: False)
201
202
        :param path_verbose_out(str):   an optional output directory for intermediate results
                                        (if not given, no intermediate results are written to disk)
203
204
        :param q(bool):                 quiet mode (default: False)
        :param ignore_errors(bool):     Useful for batch processing. (default: False)
205
206
207
208
209
210
                                        In case of error COREG.success == False and COREG.x_shift_px/COREG.y_shift_px
                                        is None
        """

        self.params              = dict([x for x in locals().items() if x[0] != "self"])

211
        # assertions
212
        assert gdal.GetDriverByName(fmt_out), "'%s' is not a supported GDAL driver." % fmt_out
213
214
        if match_gsd and out_gsd: warnings.warn("'-out_gsd' is ignored because '-match_gsd' is set.\n")
        if out_gsd:  assert isinstance(out_gsd, list) and len(out_gsd) == 2, 'out_gsd must be a list with two values.'
215
216
217
218
        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)]
219
220
        if nodata: assert isinstance(nodata, tuple) and len(nodata) == 2, "'nodata' must be a tuple with two values." \
                                                                          "Got %s with length %s." %(type(nodata),len(nodata))
221
        for rspAlg in [resamp_alg_deshift, resamp_alg_calc]:
222
            assert rspAlg in _dict_rspAlg_rsp_Int.keys(), "'%s' is not a supported resampling algorithm." % rspAlg
223
        if resamp_alg_calc=='average' and (v or not q):
224
            warnings.warn("The resampling algorithm 'average' causes sinus-shaped patterns in fft images that will "
225
226
                          "affect the precision of the calculated spatial shifts! It is highly recommended to "
                          "choose another resampling algorithm.")
227
228

        self.path_out            = path_out            # updated by self.set_outpathes
229
        self.fmt_out             = fmt_out
230
        self.out_creaOpt         = out_crea_options
231
232
233
234
235
236
237
        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
238
        self.target_xyGrid       = target_xyGrid
239
240
        self.rspAlg_DS           = resamp_alg_deshift
        self.rspAlg_calc         = resamp_alg_calc
241
        self.calc_corners        = calc_corners
Daniel Scheffler's avatar
Daniel Scheffler committed
242
        self.CPUs                = CPUs
243
244
245
246
        self.bin_ws              = binary_ws
        self.force_quadratic_win = force_quadratic_win
        self.v                   = v
        self.path_verbose_out    = path_verbose_out
247
248
249
        self.q                   = q if not v else False # overridden by v
        self.progress            = progress if not q else False  # overridden by q

250
251
252
253
        self.ignErr              = ignore_errors
        self.max_win_sz_changes  = 3                   # TODO: änderung der window size, falls nach max_iter kein valider match gefunden
        self.ref                 = None                # set by self.get_image_params
        self.shift               = None                # set by self.get_image_params
254
255
256
257
        self.matchBox            = None                # set by self.get_clip_window_properties()  => boxObj
        self.otherBox            = None                # set by self.get_clip_window_properties()  => boxObj
        self.matchWin            = None                # set by self._get_image_windows_to_match() => GeoArray
        self.otherWin            = None                # set by self._get_image_windows_to_match() => GeoArray
258
259
260
        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()
261
        self.imfft_gsd           = None                # set by self.get_clip_window_properties()
262
        self.fftw_works          = None                # set by self._calc_shifted_cross_power_spectrum()
263
        self.fftw_win_size_YX    = None                # set by calc_shifted_cross_power_spectrum()
264
265
266
267
268

        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()
269
270
        self.vec_length_map      = None
        self.vec_angle_deg       = None
271
        self.updated_map_info    = None                # set by self.get_updated_map_info()
272
273
274
        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
275
        self.shift_reliability   = None                # set by self.calculate_spatial_shifts()
276
277

        self.tracked_errors      = []                  # expanded each time an error occurs
278
        self.success             = None                # default
279
        self.deshift_results     = None                # set by self.correct_shifts()
280
281
282
283

        gdal.AllRegister()
        self._get_image_params()
        self._set_outpathes(im_ref, im_tgt)
284
        self.grid2use = 'ref' if self.shift.xgsd <= self.ref.xgsd else 'shift'
285
286
        if self.v: print('resolutions: ', self.ref.xgsd, self.shift.xgsd)

287
        self._get_overlap_properties()
288
289
290
291
292
293
294
295
296
297
298

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

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

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

301
        if self.v and self.path_verbose_out and self.matchBox.mapPoly and self.success is not False:
302
            IO.write_shp(os.path.join(self.path_verbose_out, 'poly_matchWin.shp'),
303
                         self.matchBox.mapPoly, self.matchBox.prj)
304

305
        self.success     = False if self.success is False or not self.matchBox.boxMapYX else None
306
        self._coreg_info = None # private attribute to be filled by self.coreg_info property
307
308


309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
    def _handle_error(self, error, warn=False, warnMsg=None):
        """Appends the given error to self.tracked_errors, sets self.success to False and raises the error in case
        self.ignore_errors = True.

        :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
            print('\nWARNING: '+warnMsg)

        if not self.ignErr:
            raise error


332
    def _set_outpathes(self, im_ref, im_tgt):
333
334
335
336
        assert isinstance(im_ref, (GeoArray, str)) and isinstance(im_tgt, (GeoArray, str)),\
            'COREG._set_outpathes() expects two file pathes (string) or two instances of the ' \
            'GeoArray class. Received %s and %s.' %(type(im_ref), type(im_tgt))

337
338
339
340
341
342
        get_baseN = lambda path: os.path.splitext(os.path.basename(path))[0]

        # get input pathes
        path_im_ref = im_ref.filePath if isinstance(im_ref, GeoArray) else im_ref
        path_im_tgt = im_tgt.filePath if isinstance(im_tgt, GeoArray) else im_tgt

343
344
345
346
347
        if self.path_out: # this also applies to self.path_out='auto'

            if self.path_out == 'auto':
                dir_out, fName_out = os.path.dirname(path_im_tgt), ''
            else:
348
                dir_out, fName_out = os.path.split(self.path_out)
349
350
351
352
353
354
355
356
357
358
359
360
361
362

            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:
363
364
365
366
367
                    ext         = 'bsq' if self.fmt_out=='ENVI' else \
                                    gdal.GetDriverByName(self.fmt_out).GetMetadataItem(gdal.DMD_EXTENSION)
                    fName_out   = fName_out if not fName_out 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
368

369
                self.path_out   = os.path.abspath(os.path.join(dir_out,fName_out))
370
371
372
373

                assert ' ' not in self.path_out, \
                    "The path of the output image contains whitespaces. This is not supported by GDAL."
        else:
374
            # this only happens if COREG is not instanced from within Python and self.path_out is explicitly set to None
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
            # => 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:
                        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))))
                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

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


    def _get_image_params(self):
401
402
        self.ref   = GeoArray_CoReg(self.params,'ref')
        self.shift = GeoArray_CoReg(self.params,'shift')
403
        assert prj_equal(self.ref.prj, self.shift.prj), \
404
405
            'Input projections are not equal. Different projections are currently not supported. Got %s / %s.'\
            %(get_proj4info(proj=self.ref.prj), get_proj4info(proj=self.shift.prj))
406
407


408
409
410
411
412
413
414
415
416
417
418
    def _get_overlap_properties(self):
        overlap_tmp                   = get_overlap_polygon(self.ref.poly, self.shift.poly, self.v)
        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']

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

        # overlap are must at least cover 16*16 pixels
        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
419
        assert px_covered > 16*16, 'Overlap area covers only %s pixels. At least 16*16 pixels are needed.' %px_covered
420
421


422
423
424
425
426
    def equalize_pixGrids(self):
        """
        Equalize image grids and projections of reference and target image (align target to reference).
        """
        if not (prj_equal(self.ref.prj, self.shift.prj) and self.ref.xygrid_specs==self.shift.xygrid_specs):
Daniel Scheffler's avatar
Daniel Scheffler committed
427
428
            if not self.q: print("Equalizing pixel grids and projections of reference and target image...")

429
430
            if self.grid2use=='ref':
                # resample target image to refernce image
Daniel Scheffler's avatar
Daniel Scheffler committed
431
                self.shift.arr = self.shift[:,:,self.shift.band4match] # resample the needed band only
432
                self.shift.reproject_to_new_grid(prototype=self.ref, CPUs=self.CPUs)
Daniel Scheffler's avatar
Daniel Scheffler committed
433
                self.shift.band4match = 0 # after resampling there is only one band in the GeoArray
434
435
436
            else:
                # resample reference image to target image
                # FIXME in case of different projections this will change the projection of the reference image!
Daniel Scheffler's avatar
Daniel Scheffler committed
437
                self.ref.arr = self.ref[:,:,self.ref.band4match] # resample the needed band only
438
                self.ref.reproject_to_new_grid(prototype=self.shift, CPUs=self.CPUs)
Daniel Scheffler's avatar
Daniel Scheffler committed
439
                self.ref.band4match = 0  # after resampling there is only one band in the GeoArray
440
441


442
443
444
445
446
447
448
449
450
    def show_image_footprints(self):
        """This method is intended to be called from Jupyter Notebook and shows a web map containing the calculated
        footprints of the input images as well as the corresponding overlap area."""
        # TODO different colors for polygons
        assert self.overlap_poly, 'Please calculate the overlap polygon first.'

        try:
            import folium, geojson
        except ImportError:
451
452
            folium, geojson = None, None
        if not folium or not geojson:
453
454
455
            raise ImportError("This method requires the libraries 'folium' and 'geojson'. They can be installed with "
                              "the shell command 'pip install folium geojson'.")

456
457
458
459
        refPoly      = reproject_shapelyGeometry(self.ref  .poly      , self.ref  .epsg, 4326)
        shiftPoly    = reproject_shapelyGeometry(self.shift.poly      , self.shift.epsg, 4326)
        overlapPoly  = reproject_shapelyGeometry(self.overlap_poly    , self.shift.epsg, 4326)
        matchBoxPoly = reproject_shapelyGeometry(self.matchBox.mapPoly, self.shift.epsg, 4326)
460
461

        m = folium.Map(location=tuple(np.array(overlapPoly.centroid.coords.xy).flatten())[::-1])
462
        for poly in [refPoly, shiftPoly, overlapPoly, matchBoxPoly]:
463
464
465
466
467
            gjs = geojson.Feature(geometry=poly, properties={})
            folium.GeoJson(gjs).add_to(m)
        return m


468
469
    def show_matchWin(self, figsize=(15,15), interactive=True, deshifted=False):
        """Show the image content within the matching window.
470

471
472
473
474
475
        :param figsize:      <tuple> figure size
        :param interactive:  <bool> whether to return an interactive figure based on 'holoviews' library
        :param deshifted:    <bool> whether to put the image content AFTER shift correction into the figure
        :return:
        """
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
        if interactive:
            # use Holoviews
            try:
                import holoviews as hv
            except ImportError:
                hv =None
            if not hv:
                raise ImportError(
                    "This method requires the library 'holoviews'. It can be installed for Anaconda with "
                    "the shell command 'conda install -c ioam holoviews bokeh'.")
            warnings.filterwarnings('ignore')
            hv.notebook_extension('matplotlib')
            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'
495
496
            otherWin_corr       = self._get_deshifted_otherWin()
            xmin,xmax,ymin,ymax = self.matchBox.boundsMap
497
498
499
500


            get_vmin     = lambda arr: np.percentile(arr, 2)
            get_vmax     = lambda arr: np.percentile(arr, 98)
501
502
503
            rescale      = lambda arr: rescale_intensity(arr, in_range=(get_vmin(arr), get_vmax(arr)))
            get_arr      = lambda geoArr: rescale(np.ma.masked_equal(geoArr[:], geoArr.nodata))
            get_hv_image = lambda geoArr: hv.Image(get_arr(geoArr), bounds=(xmin,ymin,xmax,ymax))(
504
                style={'cmap':'gray',
505
                       'vmin':get_vmin(geoArr[:]), 'vmax':get_vmax(geoArr[:]), # does not work
506
                       'interpolation':'none'},
507
                plot={'fig_inches':figsize, 'show_grid':True})
508
509
                #plot={'fig_size':100, 'show_grid':True})

510
511
512
            imgs_orig = {1 : get_hv_image(self.matchWin), 2 : get_hv_image(self.otherWin)}
            imgs_corr = {1 : get_hv_image(self.matchWin), 2 : get_hv_image(otherWin_corr)}
            #layout = get_hv_image(self.matchWin) + get_hv_image(self.otherWin)
513

514
515
            imgs = {1 : get_hv_image(self.matchWin) + get_hv_image(self.matchWin),
                    2 : get_hv_image(self.otherWin) + get_hv_image(otherWin_corr)
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
                        }

            # Construct a HoloMap by evaluating the function over all the keys
            hmap_orig = hv.HoloMap(imgs_orig, kdims=['image'])
            hmap_corr = hv.HoloMap(imgs_corr, kdims=['image'])

            hmap      = hv.HoloMap(imgs, kdims=['image']).collate().cols(1) # displaying this results in a too small figure
            #hmap = hv.HoloMap(imgs_corr, kdims=['image']) +  hv.HoloMap(imgs_corr, kdims=['image'])

            ## Construct a HoloMap by defining the sampling on the Dimension
            #dmap = hv.DynamicMap(image_slice, kdims=[hv.Dimension('z_axis', values=keys)])
            warnings.filterwarnings('default')
            #return hmap

            return hmap_orig if not deshifted else hmap_corr

532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
        else:
            # TODO add titles
            self.matchWin.show(figsize=figsize)
            if deshifted:
                self._get_deshifted_otherWin().show(figsize=figsize)
            else:
                self.otherWin.show(figsize=figsize)


    def show_cross_power_spectrum(self, interactive=False):
        """
        Shows a 3D surface of the cross power spectrum resulting from phase correlating the reference and target
        image within the matching window.

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

        if interactive:
            # create plotly 3D surface

            #import plotly.plotly as py # online mode -> every plot is uploaded into online plotly account
            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()
            data   = [go.Surface(z=z_data)]
            layout = go.Layout(
                title='cross power spectrum',
                autosize=False,
                width=1000,
                height=1000,
                margin=dict(l=65, r=50, b=65, t=90))
            fig    = go.Figure(data=data, layout=layout)

            return iplot(fig, filename='SCPS')

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

576

577
    def _get_opt_winpos_winsize(self):
578
        # type: (tuple,tuple) -> None
579
580
581
582
        """
        Calculates optimal window position and size in reference image units according to DGM, cloud_mask and
        trueCornerLonLat.
        """
583
584
585
586
587
588
589
590
591
        # 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)
        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))
        wp = tuple(wp)

        if None in wp:
592
            # use centroid point if possible
593
594
595
            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])

596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
            # validate window position
            if not self.overlap_poly.contains(Point(wp)):
                # 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]

            assert self.overlap_poly.contains(Point(wp))

        else:
            # validate window position
            if not self.overlap_poly.contains(Point(wp)):
                self._handle_error(ValueError('The provided window position %s/%s is outside of the overlap ' \
                                              'area of the two input images. Check the coordinates.' % wp))
616
617
618
619
620
621

        # 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)

622
                if im.mask_baddata[int(imY), int(imX)] is True:
623
                    self._handle_error(
624
625
626
                        RuntimeError('According to the provided bad data mask for the %s the chosen window position '
                            '%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])))
627

628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
        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)


    def _get_clip_window_properties(self):
        """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.
        hint: Even if X- and Y-dimension of the target window is equal, the output window can be NOT quadratic!
        """
        # FIXME image sizes like 10000*256 are still possible

        wpX,wpY             = self.win_pos_XY
        wsX,wsY             = self.win_size_XY
        ref_wsX, ref_wsY    = (wsX*self.ref.xgsd  , wsY*self.ref.ygsd)   # image units -> map units
        shift_wsX,shift_wsY = (wsX*self.shift.xgsd, wsY*self.shift.ygsd) # image units -> map units
        ref_box_kwargs      = {'wp':(wpX,wpY),'ws':(ref_wsX,ref_wsY)    ,'gt':self.ref.gt  }
        shift_box_kwargs    = {'wp':(wpX,wpY),'ws':(shift_wsX,shift_wsY),'gt':self.shift.gt}
645
646
        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)
647
648
649
        overlapWin          = boxObj(mapPoly=self.overlap_poly,gt=self.ref.gt)

        # clip matching window to overlap area
650
651
652
653
654
655
656
657
658
659
660
661
662
        matchBox.mapPoly = matchBox.mapPoly.intersection(overlapWin.mapPoly)

        #check if matchBox extent touches no data area of the image -> if yes: shrink it
        overlapPoly_within_matchWin = matchBox.mapPoly.intersection(self.overlap_poly)
        if overlapPoly_within_matchWin.area < matchBox.mapPoly.area:
            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))
            while True:
                box.buffer_imXY(1,1)
                if not box.mapPoly.within(overlapPoly_within_matchWin):
                    box.buffer_imXY(-1, -1)
                    matchBox = box
                    break
663
664
665

        # move matching window to imref grid or im2shift grid
        mW_rows, mW_cols = (self.ref.rows, self.ref.cols) if self.grid2use == 'ref' else (self.shift.rows, self.shift.cols)
666
        matchBox.mapPoly = move_shapelyPoly_to_image_grid(matchBox.mapPoly, matchBox.gt, mW_rows, mW_cols, 'NW')
667

668
669
        # check, ob durch Verschiebung auf Grid die matchBox außerhalb von overlap_poly geschoben wurde
        if not matchBox.mapPoly.within(overlapWin.mapPoly):
670
            # matchPoly weiter verkleinern # 1 px buffer reicht, weil window nur auf das Grid verschoben wurde
671
672
            xLarger,yLarger = matchBox.is_larger_DimXY(overlapWin.boundsIm)
            matchBox.buffer_imXY(-1 if xLarger else 0, -1 if yLarger else 0)
673
674

        # matching_win direkt auf grid2use (Rundungsfehler bei Koordinatentrafo beseitigen)
675
        matchBox.imPoly = round_shapelyPoly_coords(matchBox.imPoly, precision=0, out_dtype=int)
676
677

        # Check, ob match Fenster größer als anderes Fenster
678
        if not (matchBox.mapPoly.within(otherBox.mapPoly) or matchBox.mapPoly==otherBox.mapPoly):
679
            # dann für anderes Fenster kleinstes Fenster finden, das match-Fenster umgibt
680
            otherBox.boxImYX = get_smallest_boxImYX_that_contains_boxMapYX(matchBox.boxMapYX,otherBox.gt)
681
682

        # evtl. kann es sein, dass bei Shift-Fenster-Vergrößerung das shift-Fenster zu groß für den overlap wird
Daniel Scheffler's avatar
Daniel Scheffler committed
683
        t_start = time.time()
684
        while not otherBox.mapPoly.within(overlapWin.mapPoly):
Daniel Scheffler's avatar
Daniel Scheffler committed
685
            # -> match Fenster verkleinern und neues otherBox berechnen
686
687
688
689
            xLarger, yLarger = otherBox.is_larger_DimXY(overlapWin.boundsIm)
            matchBox.buffer_imXY(-1 if xLarger else 0, -1 if yLarger else 0)
            previous_area    = otherBox.mapPoly.area
            otherBox.boxImYX = get_smallest_boxImYX_that_contains_boxMapYX(matchBox.boxMapYX,otherBox.gt)
690

Daniel Scheffler's avatar
Daniel Scheffler committed
691
692
693
            if previous_area == otherBox.mapPoly.area or time.time()-t_start > 1.5:
                # happens e.g in case of a triangular footprint
                # NOTE: first condition is not always fulfilled -> therefore added timeout of 1.5 sec
694
                self._handle_error(
695
696
                    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 '
697
698
                                 'been computed correctly.' +
                                 (' Matching window shrinking timed out.' if time.time() - t_start > 5 else ''))  )
699
700
                break # break out of while loop in order to avoid that code gets stuck here

Daniel Scheffler's avatar
Daniel Scheffler committed
701
702
703
704
705
706
707
        # output validation
        for winBox in [matchBox, otherBox]:
            if winBox.imDimsYX[0] < 16 or winBox.imDimsYX[1] < 16:
                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
708

709
        if self.success is not False:
Daniel Scheffler's avatar
Daniel Scheffler committed
710
711
712
713
            # check result -> ProgrammingError if not fulfilled
            within_equal = lambda inner, outer: inner.within(outer) or inner.equals(outer)
            assert within_equal(matchBox.mapPoly, otherBox.mapPoly)
            assert within_equal(otherBox.mapPoly, overlapWin.mapPoly)
714
715

            self.imfft_gsd              = self.ref.xgsd       if self.grid2use =='ref' else self.shift.xgsd
716
717
            self.ref.win,self.shift.win = (matchBox,otherBox) if self.grid2use =='ref' else (otherBox,matchBox)
            self.matchBox,self.otherBox = matchBox, otherBox
718
719
            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])
720
            match_win_size_XY           = tuple(reversed([int(i) for i in matchBox.imDimsYX]))
721

722
723
724
            if not self.q and match_win_size_XY != self.win_size_XY:
                print('Target window size %s not possible due to too small overlap area or window position too close '
                      'to an image edge. New matching window size: %s.' %(self.win_size_XY,match_win_size_XY))
725

726
727
            #IO.write_shp('/misc/hy5/scheffler/Temp/matchMapPoly.shp', matchBox.mapPoly,matchBox.prj)
            #IO.write_shp('/misc/hy5/scheffler/Temp/otherMapPoly.shp', otherBox.mapPoly,otherBox.prj)
728
729
730
731
732
733
734


    def _get_image_windows_to_match(self):
        """Reads the matching window and the other window using subset read, and resamples the other window to the
        resolution and the pixel grid of the matching window. The result consists of two images with the same
        dimensions and exactly the same corner coordinates."""

735
736
        match_fullGeoArr = self.ref   if self.grid2use=='ref' else self.shift
        other_fullGeoArr = self.shift if self.grid2use=='ref' else self.ref
737
738

        # matchWin per subset-read einlesen -> self.matchWin.data
739
        rS, rE, cS, cE = GEO.get_GeoArrayPosition_from_boxImYX(self.matchBox.boxImYX)
Daniel Scheffler's avatar
Daniel Scheffler committed
740
741
742
743
        assert np.array_equal(np.abs(np.array([rS,rE,cS,cE])), np.array([rS,rE,cS,cE])) and \
            rE <= match_fullGeoArr.rows and cE <= match_fullGeoArr.cols, \
            'Requested area is not completely within the input array for %s.' %match_fullGeoArr.imName
        self.matchWin = GeoArray(match_fullGeoArr[rS:rE+1,cS:cE+1, match_fullGeoArr.band4match],
744
745
746
747
                                 geotransform = GEO.get_subset_GeoTransform(match_fullGeoArr.gt, self.matchBox.boxImYX),
                                 projection   = copy(match_fullGeoArr.prj),
                                 nodata       = copy(match_fullGeoArr.nodata))
        self.matchWin.imID = match_fullGeoArr.imID
748
749

        # otherWin per subset-read einlesen
750
        rS, rE, cS, cE = GEO.get_GeoArrayPosition_from_boxImYX(self.otherBox.boxImYX)
Daniel Scheffler's avatar
Daniel Scheffler committed
751
752
753
754
        assert np.array_equal(np.abs(np.array([rS,rE,cS,cE])), np.array([rS,rE,cS,cE])) and \
            rE <= other_fullGeoArr.rows and cE <= other_fullGeoArr.cols, \
            'Requested area is not completely within the input array for %s.' %other_fullGeoArr.imName
        self.otherWin = GeoArray(other_fullGeoArr[rS:rE+1, cS:cE+1, other_fullGeoArr.band4match],
755
756
757
758
                                 geotransform = GEO.get_subset_GeoTransform(other_fullGeoArr.gt, self.otherBox.boxImYX),
                                 projection   = copy(other_fullGeoArr.prj),
                                 nodata       = copy(other_fullGeoArr.nodata))
        self.otherWin.imID = other_fullGeoArr.imID
759
760
761

        #self.matchWin.deepcopy_array()
        #self.otherWin.deepcopy_array()
762
763
764

        if self.v:
            print('Original matching windows:')
765
766
            ref_data, shift_data =  (self.matchWin[:], self.otherWin[:]) if self.grid2use=='ref' else \
                                    (self.otherWin[:], self.matchWin[:])
767
768
            PLT.subplot_imshow([ref_data, shift_data],[self.ref.title,self.shift.title], grid=True)

769
        # resample otherWin.arr to the resolution of matchWin AND make sure the pixel edges are identical
770
771
        # (in order to make each image show the same window with the same coordinates)
        # TODO replace cubic resampling by PSF resampling - average resampling leads to sinus like distortions in the fft image that make a precise coregistration impossible. Thats why there is currently no way around cubic resampling.
772
        tgt_xmin,tgt_xmax,tgt_ymin,tgt_ymax = self.matchBox.boundsMap
773
774
775
776
777
778
779
780
781
782
783
784

        # equalize pixel grids and projection of matchWin and otherWin (ONLY if grids are really different)
        if not(self.matchWin.xygrid_specs==self.otherWin.xygrid_specs and
            prj_equal(self.matchWin.prj, self.otherWin.prj)):
            self.otherWin.arr, self.otherWin.gt = warp_ndarray(self.otherWin.arr,
                                                               self.otherWin.gt,
                                                               self.otherWin.prj,
                                                               self.matchWin.prj,
                                                               out_gsd    = (self.imfft_gsd, self.imfft_gsd),
                                                               out_bounds = ([tgt_xmin, tgt_ymin, tgt_xmax, tgt_ymax]),
                                                               rspAlg     = _dict_rspAlg_rsp_Int[self.rspAlg_calc],
                                                               in_nodata  = self.otherWin.nodata,
Daniel Scheffler's avatar
Daniel Scheffler committed
785
                                                               CPUs       = self.CPUs,
786
                                                               progress   = False) [:2]
787
788

        if self.matchWin.shape != self.otherWin.shape:
789
790
791
792
793
794
            self._handle_error(
                RuntimeError('Catched a possible ProgrammingError at window position %s: Bad output of '
                             'get_image_windows_to_match. Reference image shape is %s whereas shift '
                             'image shape is %s.' % (str(self.matchBox.wp),self.matchWin.shape, self.otherWin.shape)),
                warn=True)

Daniel Scheffler's avatar
Daniel Scheffler committed
795
        # check of odd dimensions of output images
796
797
        rows, cols = [i if i % 2 == 0 else i - 1 for i in self.matchWin.shape]
        self.matchWin.arr, self.otherWin.arr = self.matchWin.arr[:rows, :cols], self.otherWin.arr[:rows, :cols]
Daniel Scheffler's avatar
Daniel Scheffler committed
798
799
800
        if self.matchWin.box.imDimsYX != self.matchBox.imDimsYX:
            self.matchBox = self.matchWin.box # update matchBox
            self.otherBox = self.otherWin.box # update otherBox
801

802
        assert self.matchWin.arr is not None and self.otherWin.arr is not None, 'Creation of matching windows failed.'
803
804
805
806


    @staticmethod
    def _shrink_winsize_to_binarySize(win_shape_YX, target_size=None):
807
        # type: (tuple, tuple, int , int) -> any
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
        """Shrinks a given window size to the closest binary window size (a power of 2) -
        separately for X- and Y-dimension.

        :param win_shape_YX:    <tuple> source window shape as pixel units (rows,colums)
        :param target_size:     <tuple> source window shape as pixel units (rows,colums)
        """

        binarySizes   = [2**i for i in range(3,14)] # [8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192]
        possibSizes_X = [i for i in binarySizes if i <= win_shape_YX[1]]
        possibSizes_Y = [i for i in binarySizes if i <= win_shape_YX[0]]
        if possibSizes_X and possibSizes_Y:
            tgt_size_X,tgt_size_Y = target_size if target_size else (max(possibSizes_X),max(possibSizes_Y))
            closest_to_target_X = int(min(possibSizes_X, key=lambda x:abs(x-tgt_size_X)))
            closest_to_target_Y = int(min(possibSizes_Y, key=lambda y:abs(y-tgt_size_Y)))
            return closest_to_target_Y,closest_to_target_X
        else:
            return None


    def _calc_shifted_cross_power_spectrum(self, im0=None, im1=None, precision=np.complex64):
        """Calculates shifted cross power spectrum for quantifying x/y-shifts.

830
831
832
833
        :param im0:         reference image
        :param im1:         subject image to shift
        :param precision:   to be quantified as a datatype
        :return:            2D-numpy-array of the shifted cross power spectrum
834
835
        """

836
837
838
        im0 = im0 if im0 is not None else self.matchWin[:] if self.matchWin.imID=='ref'   else self.otherWin[:]
        im1 = im1 if im1 is not None else self.otherWin[:] if self.otherWin.imID=='shift' else self.matchWin[:]

839
840
841
842
843
        assert im0.shape == im1.shape, 'The reference and the target image must have the same dimensions.'
        if im0.shape[0]%2!=0: warnings.warn('Odd row count in one of the match images!')
        if im1.shape[1]%2!=0: warnings.warn('Odd column count in one of the match images!')

        wsYX = self._shrink_winsize_to_binarySize(im0.shape) if self.bin_ws              else im0.shape
844
        wsYX = ((min(wsYX),) * 2                             if self.force_quadratic_win else wsYX) if wsYX else None
845
846
847

        if wsYX:
            time0 = time.time()
848
849
850
851
852
            if self.v:
                print('final window size: %s/%s (X/Y)' % (wsYX[1], wsYX[0]))
                # FIXME size of self.matchWin is not updated
                # FIXME CoRegPoints_grid.WIN_SZ is taken from self.matchBox.imDimsYX but this is not updated

853
854
855
            center_YX = np.array(im0.shape)/2
            xmin,xmax,ymin,ymax = int(center_YX[1]-wsYX[1]/2), int(center_YX[1]+wsYX[1]/2),\
                                  int(center_YX[0]-wsYX[0]/2), int(center_YX[0]+wsYX[0]/2)
856

857
858
859
860
861
862
863
            in_arr0  = im0[ymin:ymax,xmin:xmax].astype(precision)
            in_arr1  = im1[ymin:ymax,xmin:xmax].astype(precision)

            if self.v:
                PLT.subplot_imshow([in_arr0.astype(np.float32), in_arr1.astype(np.float32)],
                               ['FFTin '+self.ref.title,'FFTin '+self.shift.title], grid=True)

864
            if pyfftw and self.fftw_works is not False: # if module is installed and working
865
866
                fft_arr0 = pyfftw.FFTW(in_arr0,np.empty_like(in_arr0), axes=(0,1))()
                fft_arr1 = pyfftw.FFTW(in_arr1,np.empty_like(in_arr1), axes=(0,1))()
867
868
869
870
871
872
873
874
875

                # catch empty output arrays (for some reason this happens sometimes..) -> use numpy fft
                if self.fftw_works is None and (np.std(fft_arr0)==0 or np.std(fft_arr1)==0):
                    self.fftw_works = False
                    # recreate input arrays and use numpy fft as fallback
                    in_arr0 = im0[ymin:ymax, xmin:xmax].astype(precision)
                    in_arr1 = im1[ymin:ymax, xmin:xmax].astype(precision)
                    fft_arr0 = np.fft.fft2(in_arr0)
                    fft_arr1 = np.fft.fft2(in_arr1)
876
877
                else:
                    self.fftw_works = True
878
879
880
            else:
                fft_arr0 = np.fft.fft2(in_arr0)
                fft_arr1 = np.fft.fft2(in_arr1)
881

882
883
884
            #GeoArray(fft_arr0.astype(np.float32)).show(figsize=(15,15))
            #GeoArray(fft_arr1.astype(np.float32)).show(figsize=(15,15))

885
886
887
888
889
            if self.v: print('forward FFTW: %.2fs' %(time.time() -time0))

            eps = np.abs(fft_arr1).max() * 1e-15
            # cps == cross-power spectrum of im0 and im2

890
            temp = np.array(fft_arr0 * fft_arr1.conjugate()) / (np.abs(fft_arr0) * np.abs(fft_arr1) + eps)
891
892
893

            time0 = time.time()
            if 'pyfft' in globals():
894
                ifft_arr = pyfftw.FFTW(temp,np.empty_like(temp), axes=(0,1), direction='FFTW_BACKWARD')()
895
896
897
898
899
            else:
                ifft_arr = np.fft.ifft2(temp)
            if self.v: print('backward FFTW: %.2fs' %(time.time() -time0))

            cps = np.abs(ifft_arr)
900
            # scps = shifted cps  => shift the zero-frequency component to the center of the spectrum
901
902
903
904
905
906
907
            scps = np.fft.fftshift(cps)
            if self.v:
                PLT.subplot_imshow([in_arr0.astype(np.uint16), in_arr1.astype(np.uint16), fft_arr0.astype(np.uint8),
                                fft_arr1.astype(np.uint8), scps], titles=['matching window im0', 'matching window im1',
                                "fft result im0", "fft result im1", "cross power spectrum"], grid=True)
                PLT.subplot_3dsurface(scps.astype(np.float32))
        else:
908
909
            scps = None
            self._handle_error(
910
911
912
913
914
915
916
917
                RuntimeError('The matching window became too small for calculating a reliable match. Matching failed.'))

        self.fftw_win_size_YX = wsYX
        return scps


    @staticmethod
    def _get_peakpos(scps):
918
919
920
921
922
        """Returns the row/column position of the peak within the given cross power spectrum.

        :param scps: <np.ndarray> shifted cross power spectrum
        :return:     <np.ndarray> [row, column>
        """
923
        max_flat_idx = np.argmax(scps)
924
        return np.array(np.unravel_index(max_flat_idx, scps.shape))
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966


    @staticmethod
    def _get_shifts_from_peakpos(peakpos, arr_shape):
        y_shift = peakpos[0]-arr_shape[0]//2
        x_shift = peakpos[1]-arr_shape[1]//2
        return x_shift,y_shift


    @staticmethod
    def _clip_image(im, center_YX, winSzYX): # TODO this is also implemented in GeoArray
        get_bounds = lambda YX,wsY,wsX: (int(YX[1]-(wsX/2)),int(YX[1]+(wsX/2)),int(YX[0]-(wsY/2)),int(YX[0]+(wsY/2)))
        wsY,wsX    = winSzYX
        xmin,xmax,ymin,ymax = get_bounds(center_YX,wsY,wsX)
        return im[ymin:ymax,xmin:xmax]


    def _get_grossly_deshifted_images(self, im0, im1, x_intshift, y_intshift): # TODO this is also implemented in GeoArray # this should update ref.win.data and shift.win.data
        # get_grossly_deshifted_im0
        old_center_YX = np.array(im0.shape)/2
        new_center_YX = [old_center_YX[0]+y_intshift, old_center_YX[1]+x_intshift]

        x_left  = new_center_YX[1]
        x_right = im0.shape[1]-new_center_YX[1]
        y_above = new_center_YX[0]
        y_below = im0.shape[0]-new_center_YX[0]
        maxposs_winsz = 2*min(x_left,x_right,y_above,y_below)

        gdsh_im0 = self._clip_image(im0, new_center_YX, [maxposs_winsz, maxposs_winsz])

        # get_corresponding_im1_clip
        crsp_im1  = self._clip_image(im1, np.array(im1.shape) / 2, gdsh_im0.shape)

        if self.v:
            PLT.subplot_imshow([self._clip_image(im0, old_center_YX, gdsh_im0.shape), crsp_im1],
                               titles=['reference original', 'target'], grid=True)
            PLT.subplot_imshow([gdsh_im0, crsp_im1], titles=['reference virtually shifted', 'target'], grid=True)
        return gdsh_im0,crsp_im1


    @staticmethod
    def _find_side_maximum(scps, v=0):
967
        centerpos     = [scps.shape[0]//2, scps.shape[1]//2]
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
        profile_left  = scps[ centerpos [0]  ,:centerpos[1]+1]
        profile_right = scps[ centerpos [0]  , centerpos[1]:]
        profile_above = scps[:centerpos [0]+1, centerpos[1]]
        profile_below = scps[ centerpos [0]: , centerpos[1]]

        if v:
            max_count_vals = 10
            PLT.subplot_2dline([[range(len(profile_left)) [-max_count_vals:], profile_left[-max_count_vals:]],
                                [range(len(profile_right))[:max_count_vals] , profile_right[:max_count_vals]],
                                [range(len(profile_above))[-max_count_vals:], profile_above[-max_count_vals:]],
                                [range(len(profile_below))[:max_count_vals:], profile_below[:max_count_vals]]],
                                titles =['Profile left', 'Profile right', 'Profile above', 'Profile below'],
                                shapetuple=(2,2))

        get_sidemaxVal_from_profile = lambda pf: np.array(pf)[::-1][1] if pf[0]<pf[-1] else np.array(pf)[1]
        sm_dicts_lr  = [{'side':si, 'value': get_sidemaxVal_from_profile(pf)} \
                        for pf,si in zip([profile_left,profile_right],['left','right'])]
        sm_dicts_ab  = [{'side':si, 'value': get_sidemaxVal_from_profile(pf)} \
                        for pf,si in zip([profile_above,profile_below],['above','below'])]
        sm_maxVal_lr = max([i['value'] for i in sm_dicts_lr])
        sm_maxVal_ab = max([i['value'] for i in sm_dicts_ab])
        sidemax_lr   = [sm for sm in sm_dicts_lr if sm['value'] is sm_maxVal_lr][0]
        sidemax_ab   = [sm for sm in sm_dicts_ab if sm['value'] is sm_maxVal_ab][0]
        sidemax_lr['direction_factor'] = {'left':-1, 'right':1} [sidemax_lr['side']]
        sidemax_ab['direction_factor'] = {'above':-1,'below':1} [sidemax_ab['side']]

        if v:
            print('Horizontal side maximum found %s. value: %s' %(sidemax_lr['side'],sidemax_lr['value']))
996
            print('Vertical side maximum found %s. value: %s'   %(sidemax_ab['side'],sidemax_ab['value']))
997
998
999
1000

        return sidemax_lr, sidemax_ab