Ejemplo n.º 1
0
    def test_calculation_of_tie_point_grid_float_coords(self):
        # NOTE: This does not test against unequaly sized output of get_image_windows_to_match().

        # overwrite gt and prj
        ref = GeoArray(self.ref_path)
        ref.to_mem()
        ref.filePath = None
        tgt = GeoArray(self.tgt_path)
        tgt.to_mem()
        tgt.filePath = None

        ref.gt = [
            330000.19999996503, 10.00000001, 0.0, 5862000.7999997628, 0.0,
            -10.00000001
        ]
        # ref.gt = [330000.1, 10.1, 0.0, 5862000.1, 0.0, -10.1]
        tgt.gt = [
            335440.19999996503, 10.00000001, 0.0, 5866490.7999997628, 0.0,
            -10.00000001
        ]
        # tgt.gt = [330000.1, 10.1, 0.0, 5862000.1, 0.0, -10.1]

        # get instance of COREG_LOCAL object
        CRL = COREG_LOCAL(ref, tgt, **dict(CPUs=32, **self.coreg_kwargs))
        CRL.calculate_spatial_shifts()
Ejemplo n.º 2
0
    def test_calculation_of_tie_point_grid(self):
        # get instance of COREG_LOCAL object
        CRL = COREG_LOCAL(self.ref_path, self.tgt_path, **self.coreg_kwargs)

        # calculate tie point grid
        CRL.calculate_spatial_shifts()

        # test tie point grid visualization
        with warnings.catch_warnings():
            warnings.filterwarnings(
                'ignore',
                category=UserWarning,
                message='Matplotlib is currently using agg, '
                'which is a non-GUI backend, so cannot show the figure.')
            CRL.view_CoRegPoints(hide_filtered=True)
            CRL.view_CoRegPoints(hide_filtered=False)
            CRL.view_CoRegPoints(shapes2plot='vectors')
            CRL.view_CoRegPoints_folium()

        # test shift correction and output writer
        CRL.correct_shifts()

        self.assertTrue(
            os.path.exists(self.coreg_kwargs['path_out']),
            'Output of local co-registration has not been written.')
    def processAlgorithm(self, parameters, context, feedback):
        """
        Here is where the processing itself takes place.
        """
        try:
            from arosics import COREG_LOCAL
        except:
            if platform.system() != 'Windows':
                # load/install extra python dependencies
                from Coregistration.utils.extra_deps import load_install_extra_deps
                feedback.pushInfo("Installing dependencies...")
                for msg_type, msg_val in load_install_extra_deps():
                    print(str(msg_val))
            try:
                from arosics import COREG_LOCAL
            except:
                msg = "\nError loading Arosics, this plugin requires additional Python packages to work. " \
                      "For Windows users, download and reinstall the plugin with this zip all-in-one with all " \
                      "the libs and dependencies. Read the install instructions here:\n\n" \
                      "https://github.com/SMByC/Coregistration-Qgis-processing#installation\n\n"
                feedback.reportError(msg, fatalError=True)
                return {}

        def get_inputfilepath(layer):
            return os.path.realpath(layer.source().split("|layername")[0])

        img_ref = get_inputfilepath(self.parameterAsRasterLayer(parameters, self.IMG_REF, context))
        img_tgt = get_inputfilepath(self.parameterAsRasterLayer(parameters, self.INPUT, context))

        align_grids = self.parameterAsBoolean(parameters, self.ALIGN_GRIDS, context)
        match_gsd = self.parameterAsBoolean(parameters, self.MATCH_GSD, context)

        grid_res = self.parameterAsInt(parameters, self.GRID_RES, context)

        window_size = self.parameterAsInt(parameters, self.WINDOW_SIZE, context)

        max_shift = self.parameterAsInt(parameters, self.MAX_SHIFT, context)
        resampling_method = self.resampling_methods[self.parameterAsEnum(parameters, self.RESAMPLING, context)][1]

        output_file = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)

        feedback.pushInfo("Image to image Co-Registration:")
        feedback.pushInfo("\nProcessing file: " + img_tgt)

        feedback.pushInfo("\nPerform automatic subpixel co-registration with Arosics...")
        feedback.pushInfo("\n(To check the complete log of the process, open the Python Console)...")
        if platform.system() == "Windows":
            feedback.reportError("\nWarning: in Windows due to restrictions to enable multiprocessing inside Qgis, "
                                 "the process could take longer. Continue with one core ...\n", fatalError=False)
        CRL = COREG_LOCAL(img_ref, img_tgt, path_out=output_file, align_grids=align_grids, match_gsd=match_gsd,
                          grid_res=grid_res, window_size=(window_size, window_size),
                          resamp_alg_deshift=resampling_method, max_shift=max_shift, max_iter=15,
                          fmt_out="GTiff", out_crea_options=["WRITE_METADATA=NO"],
                          CPUs=1 if platform.system() == "Windows" else None)
        CRL.correct_shifts()

        feedback.pushInfo("DONE\n")

        return {self.OUTPUT: output_file}
Ejemplo n.º 4
0
    def test_coreg_init_from_inMem_GeoArray(self):
        # get GeoArray instances
        self.ref_gA = GeoArray(self.ref_path)
        self.tgt_gA = GeoArray(self.tgt_path)

        # assure the raster data are in-memory
        self.ref_gA.to_mem()
        self.tgt_gA.to_mem()

        # get instance of COREG_LOCAL object
        self.CRL = COREG_LOCAL(self.ref_gA, self.tgt_gA, **self.coreg_kwargs)
Ejemplo n.º 5
0
def Arosics_test_local(ref_img, tgt_img, kwargs):
    """
    testing function for local registration in Arosics
    :param ref_img: str; full path and filename of the reference image
    :param tgt_img: str; full path and filename of the target image
    :param kwargs: dict; dictionary containing the detailed arguments for local correction.
    :return:
    """

    from arosics import COREG_LOCAL
    start = default_timer()
    CRL = COREG_LOCAL(ref_img, tgt_img, **kwargs)
    CRL.correct_shifts()
    end = default_timer()
    print(end - start)
    return CRL
Ejemplo n.º 6
0
 def setUp(cls):
     CRL = COREG_LOCAL(test_cases['INTER1']['ref_path'], test_cases['INTER1']['tgt_path'],
                       **test_cases['INTER1']['kwargs_local'])
     cls.TPG = Tie_Point_Grid(CRL.COREG_obj, CRL.grid_res,
                              max_points=100,  # limit to 100 to reduce computational load
                              outFillVal=CRL.outFillVal,
                              resamp_alg_calc=CRL.rspAlg_calc,
                              tieP_filter_level=CRL.tieP_filter_level,
                              outlDetect_settings=dict(
                                  min_reliability=CRL.min_reliability,
                                  rs_max_outlier=CRL.rs_max_outlier,
                                  rs_tolerance=CRL.rs_tolerance),
                              dir_out=CRL.projectDir,
                              CPUs=CRL.CPUs,
                              progress=CRL.progress,
                              v=CRL.v,
                              q=CRL.q)
Ejemplo n.º 7
0
    def _compute_tie_points(self):
        CRL = COREG_LOCAL(self.cfg.path_reference_image,
                          self._EnMAP_band,
                          grid_res=40,
                          max_shift=5,
                          nodata=(self._ref_Im.nodata, 0),
                          footprint_poly_tgt=reproject_shapelyGeometry(
                              self._EnMAP_Im.meta.vnir.ll_mapPoly, 4326,
                              self._EnMAP_band.epsg),
                          mask_baddata_tgt=self._EnMAP_mask)
        TPG = CRL.tiepoint_grid
        # CRL.view_CoRegPoints(shapes2plot='vectors', hide_filtered=False, figsize=(20, 20),
        #                      savefigPath='/home/gfz-fe/scheffler/temp/EnPT/Archachon_AROSICS_tiepoints.png')

        valid_tiepoints = TPG.CoRegPoints_table[
            TPG.CoRegPoints_table.OUTLIER.__eq__(False)].copy()

        return valid_tiepoints
Ejemplo n.º 8
0
def run_arosics(ref_geoArr,
                targ_geoArr,
                grid_res,
                window_size,
                path_out,
                projectDir,
                shp_output=None):
    """
        Coregister two images using Arosics package.

        Parameters:
            ref_geoArr (GeoArray): reference image.
            targ_geoArr (GeoArray): target image (to be registered).
            grid_res (int): arosics parameter: grid resolution.
            window_size ((int, int)): arosics parameter: moving window size.
            path_out (str): output path of registered image.
            projectDir (str): project directory.
            shp_output (str): output .shp directory.
    """
    kwargs = {
        'grid_res': grid_res,
        'window_size': window_size,
        'path_out': path_out,
        'projectDir': projectDir,
        'q': False,
    }

    CRL = COREG_LOCAL(ref_geoArr, targ_geoArr, **kwargs)

    CRL.correct_shifts()

    ###Visualize tie point grid with INITIAL shifts present in your input target image
    ## import matplotlib
    ## matplotlib.use("TkAgg")
    # CRL.view_CoRegPoints(figsize=(15,15), backgroundIm='ref')
    ###Visualize tie point grid with shifts present AFTER shift correction
    # CRL_after_corr = COREG_LOCAL(img_reference.format('nir'), CRL.path_out, **kwargs)
    # CRL_after_corr.view_CoRegPoints(figsize=(15,15),backgroundIm='ref')

    if shp_output is not None:
        CRL.tiepoint_grid.to_PointShapefile(path_out=shp_output)

    return
Ejemplo n.º 9
0
def run_local_coreg(args):
    CRL = COREG_LOCAL(
        args.path_ref,
        args.path_tgt,
        path_out=args.path_out,
        fmt_out=args.fmt_out,
        grid_res=args.grid_res,
        max_points=args.max_points,
        r_b4match=args.br,
        s_b4match=args.bs,
        window_size=args.ws,
        max_iter=args.max_iter,
        max_shift=args.max_shift,
        tieP_filter_level=args.tieP_filter_level,
        min_reliability=args.min_reliability,
        rs_max_outlier=args.rs_max_outlier,
        rs_tolerance=args.rs_tolerance,
        # align_grids=args.align_grids,
        # match_gsd=args.match_gsd,
        # out_gsd=args.out_gsd,
        resamp_alg_calc=args.rsp_alg_deshift,
        resamp_alg_deshift=args.rsp_alg_calc,
        data_corners_ref=args.cor0,
        data_corners_tgt=args.cor1,
        nodata=args.nodata,
        calc_corners=args.calc_cor,
        mask_baddata_ref=args.mask_ref,
        mask_baddata_tgt=args.mask_tgt,
        CPUs=None if args.mp else 1,
        force_quadratic_win=args.quadratic_win,
        binary_ws=args.bin_ws,
        progress=args.progress,
        v=args.v,
        q=args.q,
    )
    CRL.correct_shifts()
Ejemplo n.º 10
0
    def test_calculation_of_tie_point_grid(self):
        # get instance of COREG_LOCAL object
        CRL = COREG_LOCAL(self.ref_path, self.tgt_path, **self.coreg_kwargs)

        # use the getter of the CoRegPoints_table to calculate tie point grid
        # noinspection PyStatementEffect
        CRL.CoRegPoints_table

        # test tie point grid visualization
        if find_loader(
                'mpl_toolkits.basemap'):  # only works if basemap is installed
            CRL.view_CoRegPoints(hide_filtered=True)
            CRL.view_CoRegPoints(hide_filtered=False)
            CRL.view_CoRegPoints(shapes2plot='vectors')

        if find_loader('folium') and find_loader('geojson'):
            CRL.view_CoRegPoints_folium()

        # test shift correction and output writer
        CRL.correct_shifts()

        self.assertTrue(
            os.path.exists(self.coreg_kwargs['path_out']),
            'Output of local co-registration has not been written.')
Ejemplo n.º 11
0
def main():
    # dir_in = r'Z:\townsenduser-rw\HyspexPro\Output\Cheesehead_V3\CHEESEHEAD_20190626\CHEESEHEAD_20190626_02_quicklooks'
    dir_in = r'Z:\townsenduser-rw\HyspexPro\Output\Cheesehead_V3\CHEESEHEAD_20190806'
    dest_dir = dir_in + '/Deshift'
    img = '/CHEESEHEAD_20190806_03_Refl'
    # ref_img = dir_in + '/Merge' + img
    dest_file = dest_dir + img
    header = read_envi_header(dir_in + '/Merge' + img + '.hdr')
    band_vnir, band_swir, idx_vnir, idx_swir = band_select(header)
    # hyspex_extract(dir_in + '/Merge' + img, [186], dest_dir + img + '_refband')
    # hyspex_extract(dir_in + '/Merge' + img, [185], dest_dir + img + '_swir_test')

    ref_img = dest_dir + img + '_refband'
    tgt_img = dest_dir + img + '_swir_test'

    grid_ls = [350]  #[300, 350, 400, 450]
    windows = [150]  #[128, 150, 264, 280]

    for i in range(len(grid_ls)):

        out = dest_dir + '/shifted_local_03_{}_{}'.format(
            grid_ls[i], windows[i])
        g = grid_ls[i]
        w = windows[i]
        kwargs = kwargs = {
            'grid_res': g,
            'window_size': (w, w),
            'path_out': out,
            'nodata': (0, 0),
            'r_b4match': 1,
            's_b4match': 1,
            'max_iter': 10,
            'max_shift': 10,
            # 'min_reliability': 25,
            # 'tieP_filter_level': 1,
            'resamp_alg_calc': 'nearest',
            'q': False
        }

        dest_img = dest_file + '_deshift'

        # calculate the shift info
        try:
            CRL = COREG_LOCAL(ref_img, tgt_img, **kwargs)
            CRL.calculate_spatial_shifts()
            # CRL.correct_shifts()
        except:
            continue

        # apply the shift to a single band:
        band = 185
        # shift_arg = {
        #         'band2process': int(band + 1),
        #         'resamp_alg': 'nearest',
        #         'nodata': 0,
        #         'align_grids': True,
        #         'q': True
        #     }
        result = DESHIFTER(dir_in + '/Merge' + img,
                           CRL.coreg_info,
                           band2process=int(band + 1),
                           align_grids=True,
                           match_gsd=True,
                           nodata=0,
                           resamp_alg='cubic',
                           q=True).correct_shifts()
        modify_hyspex_band(dest_img, band, result['arr_shifted'])
Ejemplo n.º 12
0
 def test_coreg_init_from_disk(self):
     self.CRL = COREG_LOCAL(self.ref_path, self.tgt_path,
                            **self.coreg_kwargs)
def main():  # argv

    # set up directories
    yrs = ['2015']  #['2013', '2014', '2015', '2016', '2017', '2018']
    boxes = [
        'f150602'
    ]  #['f130612', 'f140603', 'f150601', 'f160621', 'f170607', 'f180622']
    box_name = 'Yosemite_NEON'
    dir_landsat = r'Y:\CA_timeseries\LandSAT'
    dir_avs = r'Z:\townsenduser-rw\CA_project\Raw'
    dir_out = r'G:\My Drive\Projects_ongoing\HyspIRI_Validation\TraitValidation\CA_TimeSeries\GCPs'
    gcp_save_flag = True
    nodata_tgt = -9999

    # two for loops: 1. each box; 2. each flight line

    for i, box in enumerate(boxes):
        yr = yrs[i]
        ref_img = glob.glob(f'{dir_landsat}/*{yr}*_sr_brdf.tif')[0]
        # flightline list for the box:
        dir_l = f'{dir_avs}/{yr}/{box_name}/{box}/L2'
        flights = sorted(glob.glob(f'{dir_l}/{box}*_img'))

        # only use the green band for ref:
        ref_ds = gdal.Open(ref_img)
        translate_option = gdal.TranslateOptions(
            bandList=[2], outputType=gdalconst.GDT_Float32)

        # ref_filename = '/vsimem/ref.tif'
        ref_filename = './ref.tif'
        gdal.Translate(ref_filename, ref_ds, options=translate_option)

        # loop 2: each flightline in the box:
        for j, flight in enumerate(flights):

            tgt_img = flight
            # nodata_tgt = args.nodata

            print(ref_img, tgt_img, dir_out, gcp_save_flag)

            # warp_img = '/vsimem/warp_tmp.tif'  # out_dir +'/'+os.path.basename(tgt_img).split('.tif')[0]+'_auto_warp.tif'
            warp_img = './warp_tmp.tif'
            # extract one band from target img, for AVIRIS-Classic, using band 21, wvl: 560nm
            tgt_ds = gdal.Open(tgt_img)
            gt = tgt_ds.GetGeoTransform()

            translate_option = gdal.TranslateOptions(
                bandList=[21], outputType=gdalconst.GDT_Float32)
            # translate_option = gdal.TranslateOptions(bandList=[3],outputType=gdalconst.GDT_Float32) #[3] gdalconst.GDT_Int16

            dst_filename = '/vsimem/translate.tif'

            gdal.Translate(dst_filename, tgt_ds, options=translate_option)

            gdal.Warp(warp_img, dst_filename)
            gdal.GetDriverByName('GTiff').Delete(dst_filename)

            kwargs = {
                'grid_res': 80,  # 400, # 350
                'window_size': (100, 100),  # (64, 64), #256, #150
                'path_out': None,  # out_img,
                # 'r_b4match': 187,
                # 's_b4match': 186,
                'match_gsd': False,
                'max_iter': 16,
                'max_shift': 205,
                'nodata': (0, nodata_tgt),  # (0, -0.9998),
                'CPUs': 8,
                # 'tieP_filter_level': 1, # avoid filter 2 and 3, fix the SSIM filter error
                # 'min_reliability': 25,
                'resamp_alg_calc': 'nearest',
                'resamp_alg_deshift': 'nearest',
                'align_grids': False,
                'q': True
            }

            # CRL = COREG_LOCAL(ref_img, warp_img, **kwargs)
            CRL = COREG_LOCAL(ref_filename, warp_img, **kwargs)

            try:
                CRL.calculate_spatial_shifts()
            except:
                print('{} is not processed properly'.format(tgt_img))
                # error_ls.append(tgt_img)
                # quit()
                continue
            new_coreg_info = own_copy(CRL.coreg_info)

            rot_mat = np.array([[gt[1], gt[2], gt[0]], [gt[4], gt[5], gt[3]],
                                [0, 0, 1]])
            gt_warp = gdal.Open(warp_img).GetGeoTransform()
            warp_rot_mat = np.array([[gt_warp[1], gt_warp[2], gt_warp[0]],
                                     [gt_warp[4], gt_warp[5], gt_warp[3]],
                                     [0, 0, 1]])

            inv_rot_mat = inv(rot_mat)
            update_gcp_rotation(new_coreg_info, inv_rot_mat, gt, warp_rot_mat,
                                gcp_save_flag)

            gdal.GetDriverByName('GTiff').Delete(warp_img)

            print("Totally {} GCPs are found.".format(
                len(new_coreg_info['GCPList'])))

            if not gcp_save_flag:

                out_img = dir_out + '/' + os.path.basename(tgt_img).split(
                    '.tif')[0] + '_geocorr_rot.bin'
                out_pixel_size = np.sqrt(gt[1]**2 + gt[2]**2)
                shift_arg = {
                    'band2process': None,  # int(band + 1),
                    'resamp_alg': 'nearest',
                    'CPUs': 8,
                    'out_gsd': [out_pixel_size, out_pixel_size],
                    'nodata': nodata_tgt,
                    'path_out': out_img,
                    'align_grids': False,
                    'q': True
                }

                DESHIFTER(tgt_img, new_coreg_info,
                          **shift_arg).correct_shifts()
            else:
                # save GCPs and new_coreg_info
                out_json = dir_out + '/' + os.path.basename(tgt_img).split(
                    '.tif')[0] + '_GCPs.json'
                with open(out_json, "w") as outfile:
                    json.dump(new_coreg_info, outfile)
                    print("JSON file {} for GCP is saved.".format(out_json))

            del CRL

        gdal.GetDriverByName('GTiff').Delete(ref_filename)
Ejemplo n.º 14
0
def main():
    # dir_avs = r'D:\CA_NEON\AVIRIS\Warped'
    # dir_NEON = r'D:\CA_NEON\NEON\Merged'
    # dest_dir = dir_avs + '/Deshift'
    dir_NEON = r'Z:\townsenduser-rw\CA_project\CA_NEON\NEON\Merged'
    dir_in = r'Z:\townsenduser-rw\CA_project\CA_NEON\CA_spectra_unmixing\testing'
    # img = '/CHEESEHEAD_20190806_03_Refl'
    # ref_img = dir_in + '/Merge' + img
    # dest_file = dest_dir + img
    # img = '/AVIRIS_TEAK_2017_solar4_warp'
    # header = read_envi_header(dir_avs + '/AVIRIS_TEAK_2017_solar4_warp.hdr')
    # band_vnir, band_swir, idx_vnir, idx_swir = band_select(header)
    # hyspex_extract(dir_in + '/Merge' + img, [186], dest_dir + img + '_refband')
    # hyspex_extract(dir_avs + '/AVIRIS_TEAK_2017_solar4_warp', [16], dir_avs + img + '_g')
    # img_band_extraction(dir_avs+img, 17, dir_avs + img + '_g', nodata=-9999)
    # ref_img = dir_NEON + '/TEAK_rgb_2017_v2'
    # tgt_img = dir_avs + img + '_g'
    ref_img = dir_NEON + '/TEAK_rgb_2017_v2'
    tgt_img = dir_in + '/f170607t01p00r16_rfl_v1g_img_topo_brdf_solar_g_TEAK_clipped'
    dest_img = dir_in + '/f170607t01p00r16_rfl_v1g_img_topo_brdf_solar_SVDI_v0_TEAK_clipped'
    dest_img_deshift = dest_img + '_deshift'
    # out = dir_in + '/shifted_global'
    grid_ls = [150]  #[150, 200, 300, 350]
    windows = [70]  #[70, 120, 128, 150]
    band_idx = [0, 1, 2, 3, 4]
    bandnames = ['Substrate', 'Canopy', 'Dark', 'Snow', 'RMSE']

    for i in range(len(grid_ls)):

        # out = dir_avs + '/shifted_Teak_2017_{}_{}'.format(grid_ls[i], windows[i])
        out = dir_in + '/shifted_Teak_2017_{}_{}'.format(
            grid_ls[i], windows[i])
        g = grid_ls[i]
        w = windows[i]
        kwargs = kwargs = {
            'grid_res': g,
            'window_size': (w, w),
            'path_out': out,
            'nodata': (-9999, -9999),
            'r_b4match': 2,
            's_b4match': 1,
            'max_iter': 10,
            'max_shift': 5,
            'min_reliability': 25,
            # 'tieP_filter_level': 1,
            'resamp_alg_calc': 'nearest',
            'q': False
        }
        CRL = COREG_LOCAL(ref_img, tgt_img, **kwargs)
        CRL.calculate_spatial_shifts()
        # CRL.correct_shifts()

        for j, band in enumerate(band_idx):

            result = DESHIFTER(dest_img,
                               CRL.coreg_info,
                               band2process=int(band + 1),
                               align_grids=True,
                               match_gsd=True,
                               nodata=0,
                               resamp_alg='cubic',
                               q=True).correct_shifts()
            # modify_hyspex_band(dest_img_deshift, band, result['arr_shifted'])
            # Use gdal if the deshifted array has different dimensions compared to the original one.
            if j == 0:
                driver = gdal.GetDriverByName('ENVI')

                dst_raster = driver.Create(dest_img_deshift,
                                           result['arr_shifted'].shape[1],
                                           result['arr_shifted'].shape[0],
                                           len(band_idx), gdal.GDT_Float32)
                dst_raster.SetGeoTransform(result['updated geotransform'])
                dst_raster.SetProjection(result['updated projection'])
            Gdal_write_band(dst_raster,
                            int(band + 1),
                            result['arr_shifted'],
                            bandnames[j],
                            no_data=0)
            del result
Ejemplo n.º 15
0
#im_reference = r'C:\DEV\FuelMapping\registration\Sample_Images\L2A_T14RMT_20171022T171339_B04_10m.jp2'
#im_target = r'C:\DEV\FuelMapping\registration\Sample_Images\L2A_T14RMT_20170430T171301_B04_10m.jp2'
#shiftedfn = im_target[0:-4] + "_pyshifted"  + '.tif'
#print(shiftedfn)
##print(help(CRL.correct_shifts()))
#for full band image
#im_reference = r'c:\DEV\FuelMapping\registration\Multiband_Images\S2B_MSIL2A_T14RMT_N0205_20171022_10m.tif'
#im_target = r'c:\DEV\FuelMapping\registration\Multiband_Images\S2A_MSIL2A_T14RMT_N0205_20170430_10m.tif'
#shiftedfn = im_target[0:-4] + "_pyfullbandshifted"  + '.tif'
#CRL = COREG(im_reference,im_target,shiftedfn,fmt_out='GTiff')
#CRL.correct_shifts()
#shiftedarray.save(shiftedfn,fmt='GTiff',creationOptions="WRITE_METADATA=YES")
#
#import gdal
#print(help(gdal))
#Local 
from arosics import COREG_LOCAL 
im_reference = r'C:\DEV\FuelMapping\registration\Sample_Images\L2A_T14RMT_20171022T171339_B04_10m.jp2'
im_target = r'C:\DEV\FuelMapping\registration\Sample_Images\L2A_T14RMT_20170430T171301_B04_10m.jp2'
shiftedfn = im_target[0:-4] + "_pylocalshifted"  + '.tif'
kwargs = {
    'path_out':shiftedfn,
    'fmt_out':'GTiff',
    'grid_res'     : 200,
    'window_size'  : (64,64),
    'q'            : False,
}

CRL = COREG_LOCAL(im_reference,im_target,**kwargs)
CRL.correct_shifts()
def main():
    # parameters for the geo rectification:
    kwargs = {
        'grid_res': 400,  #450, #400, # 350
        'window_size': (256, 256),  #280, #256, #150
        # 'path_out': out,
        'r_b4match': 187,
        's_b4match': 186,
        'match_gsd': True,
        'max_iter': 8,
        'max_shift': 10,
        'nodata': (0, 0),
        'tieP_filter_level':
        3,  # avoid filter 2 and 3, fix the SSIM filter error
        # 'min_reliability': 25,
        'resamp_alg_calc': 'nearest',
        'q': False
    }
    # dir_in = r'Z:\townsenduser-rw\HyspexPro\Output\Cheesehead_V3\CHEESEHEAD_20190626\CHEESEHEAD_20190626_02_quicklooks'
    dir_in = r'Z:\townsenduser-rw\HyspexPro\Output\Cheesehead_V3\CHEESEHEAD_20190830'
    # create deshift folder for deshifted Refl data:
    dest_dir = dir_in + '/Deshift'
    if not os.path.exists(dest_dir):
        os.makedirs(dest_dir)
    imgs = glob.glob(dir_in + '/Merge/*_Refl')
    imgs.sort()
    # get swir bands:
    header = read_envi_header(imgs[0] + '.hdr')
    band_vnir, band_swir, idx_vnir, idx_swir = band_select(header)
    error_ls = []

    # for left over imgs:
    imgs = [imgs[x] for x in [12]]
    for img in imgs:
        # # copy file in /Merge to Deshift:
        shutil.copy(img, dest_dir)
        # file header:
        shutil.copy(img + '.hdr', dest_dir)

        # rename files:
        img_base = os.path.basename(img)
        dest_file = os.path.join(dest_dir, img_base)
        dest_img = dest_file + '_deshift'

        #
        os.rename(dest_file, dest_img)
        dest_hdr = os.path.join(dest_dir, img_base + '.hdr')
        os.rename(dest_hdr, dest_file + '_deshift.hdr')
        del dest_file, dest_hdr

        # calculate the shift info
        CRL = COREG_LOCAL(img, img, **kwargs)
        try:
            CRL.calculate_spatial_shifts()
        except:
            print('{} is not processed properly'.format(img))
            error_ls.append(img)
            continue

        # apply the shift to all swir bands:
        for band in idx_swir:
            print('Now shifting band {}'.format(band))
            shift_arg = {
                'band2process': int(band + 1),
                'resamp_alg': 'cubic',
                'nodata': 0,
                'align_grids': True,
                'q': True
            }
            result = DESHIFTER(img, CRL.coreg_info,
                               **shift_arg).correct_shifts()
            modify_hyspex_band(dest_img, band, result['arr_shifted'])
            del result

        del CRL

    # If files are not processed properly:
    if len(error_ls) > 0:
        with open(dest_dir + '/error_files.txt', 'w') as f:
            for item in error_ls:
                f.write("%s\n" % item)