Example #1
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}
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
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
Example #5
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()
Example #6
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.')
Example #7
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()