コード例 #1
0
ファイル: neighbor_index.py プロジェクト: whaozl/ibeis
    def get_cfgstr(nnindexer, noquery=False):
        r""" returns string which uniquely identified configuration and support data

        Args:
            noquery (bool): if True cfgstr is only relevant to building the
                index. No search params are returned (default = False)

        Returns:
            str: flann_cfgstr

        CommandLine:
            python -m ibeis.algo.hots.neighbor_index --test-get_cfgstr

        Example:
            >>> # DISABLE_DOCTEST
            >>> from ibeis.algo.hots.neighbor_index import *  # NOQA
            >>> import ibeis
            >>> cfgdict = dict(fg_on=False)
            >>> qreq_ = ibeis.testdata_qreq_(defaultdb='testdb1', p='default:fg_on=False')
            >>> qreq_.load_indexer()
            >>> nnindexer = qreq_.indexer
            >>> noquery = True
            >>> flann_cfgstr = nnindexer.get_cfgstr(noquery)
            >>> result = ('flann_cfgstr = %s' % (str(flann_cfgstr),))
            >>> print(result)
            flann_cfgstr = _FLANN((algo=kdtree,seed=42,t=8,))_VECS((11260,128)gj5nea@ni0%f3aja)
        """
        flann_cfgstr_list = []
        use_params_hash = True
        use_data_hash = True
        if use_params_hash:
            flann_defaults = vt.get_flann_params(
                nnindexer.flann_params['algorithm'])
            #flann_params_clean = flann_defaults.copy()
            flann_params_clean = ut.sort_dict(flann_defaults)
            ut.updateif_haskey(flann_params_clean, nnindexer.flann_params)
            if noquery:
                ut.delete_dict_keys(flann_params_clean, ['checks'])
            shortnames = dict(algorithm='algo',
                              checks='chks',
                              random_seed='seed',
                              trees='t')
            short_params = ut.odict([
                (shortnames.get(key, key), str(val)[0:7])
                for key, val in six.iteritems(flann_params_clean)
            ])
            flann_valsig_ = ut.dict_str(short_params,
                                        nl=False,
                                        explicit=True,
                                        strvals=True)
            flann_valsig_ = flann_valsig_.lstrip('dict').replace(' ', '')
            #flann_valsig_ = str(list(flann_params.values()))
            #flann_valsig = ut.remove_chars(flann_valsig_, ', \'[]')
            flann_cfgstr_list.append('_FLANN(' + flann_valsig_ + ')')
        if use_data_hash:
            vecs_hashstr = ut.hashstr_arr(nnindexer.idx2_vec, '_VECS')
            flann_cfgstr_list.append(vecs_hashstr)
        flann_cfgstr = ''.join(flann_cfgstr_list)
        return flann_cfgstr
コード例 #2
0
ファイル: neighbor_index.py プロジェクト: Erotemic/ibeis
    def get_cfgstr(nnindexer, noquery=False):
        r""" returns string which uniquely identified configuration and support data

        Args:
            noquery (bool): if True cfgstr is only relevant to building the
                index. No search params are returned (default = False)

        Returns:
            str: flann_cfgstr

        CommandLine:
            python -m ibeis.algo.hots.neighbor_index --test-get_cfgstr

        Example:
            >>> # DISABLE_DOCTEST
            >>> from ibeis.algo.hots.neighbor_index import *  # NOQA
            >>> import ibeis
            >>> cfgdict = dict(fg_on=False)
            >>> qreq_ = ibeis.testdata_qreq_(defaultdb='testdb1', p='default:fg_on=False')
            >>> qreq_.load_indexer()
            >>> nnindexer = qreq_.indexer
            >>> noquery = True
            >>> flann_cfgstr = nnindexer.get_cfgstr(noquery)
            >>> result = ('flann_cfgstr = %s' % (str(flann_cfgstr),))
            >>> print(result)
            flann_cfgstr = _FLANN((algo=kdtree,seed=42,t=8,))_VECS((11260,128)gj5nea@ni0%f3aja)
        """
        flann_cfgstr_list = []
        use_params_hash = True
        use_data_hash = True
        if use_params_hash:
            flann_defaults = vt.get_flann_params(nnindexer.flann_params['algorithm'])
            #flann_params_clean = flann_defaults.copy()
            flann_params_clean = ut.sort_dict(flann_defaults)
            ut.updateif_haskey(flann_params_clean, nnindexer.flann_params)
            if noquery:
                ut.delete_dict_keys(flann_params_clean, ['checks'])
            shortnames = dict(algorithm='algo', checks='chks', random_seed='seed', trees='t')
            short_params = ut.odict([(shortnames.get(key, key), str(val)[0:7])
                                     for key, val in six.iteritems(flann_params_clean)])
            flann_valsig_ = ut.dict_str(
                short_params, nl=False, explicit=True, strvals=True)
            flann_valsig_ = flann_valsig_.lstrip('dict').replace(' ', '')
            #flann_valsig_ = str(list(flann_params.values()))
            #flann_valsig = ut.remove_chars(flann_valsig_, ', \'[]')
            flann_cfgstr_list.append('_FLANN(' + flann_valsig_ + ')')
        if use_data_hash:
            vecs_hashstr = ut.hashstr_arr(nnindexer.idx2_vec, '_VECS')
            flann_cfgstr_list.append(vecs_hashstr)
        flann_cfgstr = ''.join(flann_cfgstr_list)
        return flann_cfgstr
コード例 #3
0
ファイル: interact_qres2.py プロジェクト: heroinlin/ibeis
 def __init__(self, ibs, qaid2_qres, **kwargs):
     # Initialize variables. No logic
     self.fnum               = None
     self.nPerPage           = None
     self.ranks_lt           = None
     self.on_change_callback = None
     self.ibs = None
     self.nCands = 0  # number of candidate matches
     self.qaid2_qres = {}
     self.cand_match_list = []
     self.start_index = 0
     self.current_pagenum = -1
     self.current_match_aids = None
     self.current_qres       = None
     self.scope = []  # for keeping those widgets alive!
     self.nPages = 0
     self.stop_index  = -1
     self.interactkw = {
         'draw_fmatches': False,
         'draw_ell': True,
         'draw_rect': True,
         'draw_lines': True,
         'in_image': False,
         'draw_lbl': True,
         'show_timedelta': False,
     }
     self.toggleable_kws = odict([
         ('TOG: fmatch', 'draw_fmatches'),
         ('TOG: in_image', 'in_image'),
         ('TOG: timedelta', 'show_timedelta'),
         ('TOG: lbl', 'draw_lbl'),
     ])
     # Initialize Logic
     # main data
     self.ibs = ibs
     self.qaid2_qres = qaid2_qres
     # update keyword args
     params = default_interact_qres_params()
     ut.updateif_haskey(params, kwargs)
     self.__dict__.update(**params)
     # initialize matches
     self.init_candidates(qaid2_qres)
     # show first page
     self.show_page(0)
コード例 #4
0
ファイル: interact_qres2.py プロジェクト: whaozl/ibeis
 def __init__(self, ibs, qaid2_qres, **kwargs):
     # Initialize variables. No logic
     self.fnum = None
     self.nPerPage = None
     self.ranks_lt = None
     self.on_change_callback = None
     self.ibs = None
     self.nCands = 0  # number of candidate matches
     self.qaid2_qres = {}
     self.cand_match_list = []
     self.start_index = 0
     self.current_pagenum = -1
     self.current_match_aids = None
     self.current_qres = None
     self.scope = []  # for keeping those widgets alive!
     self.nPages = 0
     self.stop_index = -1
     self.interactkw = {
         'draw_fmatches': False,
         'draw_ell': True,
         'draw_rect': True,
         'draw_lines': True,
         'in_image': False,
         'draw_lbl': True,
         'show_timedelta': False,
     }
     self.toggleable_kws = odict([
         ('TOG: fmatch', 'draw_fmatches'),
         ('TOG: in_image', 'in_image'),
         ('TOG: timedelta', 'show_timedelta'),
         ('TOG: lbl', 'draw_lbl'),
     ])
     # Initialize Logic
     # main data
     self.ibs = ibs
     self.qaid2_qres = qaid2_qres
     # update keyword args
     params = default_interact_qres_params()
     ut.updateif_haskey(params, kwargs)
     self.__dict__.update(**params)
     # initialize matches
     self.init_candidates(qaid2_qres)
     # show first page
     self.show_page(0)
コード例 #5
0
ファイル: dummy.py プロジェクト: SU-ECE-17-7/vtool
def testdata_ratio_matches(fname1='easy1.png', fname2='easy2.png', **kwargs):
    r"""
    Runs simple ratio-test matching between two images.
    Technically this is not dummy data.

    Args:
        fname1 (str):
        fname2 (str):

    Returns:
        tuple : matches_testtup

    CommandLine:
        python -m vtool.tests.dummy --test-testdata_ratio_matches
        python -m vtool.tests.dummy --test-testdata_ratio_matches --help
        python -m vtool.tests.dummy --test-testdata_ratio_matches --show
        python -m vtool.tests.dummy --test-testdata_ratio_matches --show --ratio_thresh=1.1 --rotation_invariance

        python -m vtool.tests.dummy --test-testdata_ratio_matches --show --ratio_thresh=.625 --rotation_invariance --fname1 easy1.png --fname2 easy3.png
        python -m vtool.tests.dummy --test-testdata_ratio_matches --show --ratio_thresh=.625 --no-rotation_invariance --fname1 easy1.png --fname2 easy3.png

    Example:
        >>> # ENABLE_DOCTEST
        >>> from vtool.tests.dummy import *  # NOQA
        >>> import vtool as vt
        >>> # build test data
        >>> fname1 = ut.get_argval('--fname1', type_=str, default='easy1.png')
        >>> fname2 = ut.get_argval('--fname2', type_=str, default='easy2.png')
        >>> # execute function
        >>> default_dict = vt.get_extract_features_default_params()
        >>> default_dict['ratio_thresh'] = .625
        >>> kwargs = ut.argparse_dict(default_dict)
        >>> matches_testtup = testdata_ratio_matches(fname1, fname2, **kwargs)
        >>> (kpts1, kpts2, fm_RAT, fs_RAT, rchip1, rchip2) = matches_testtup
        >>> if ut.show_was_requested():
        >>>     import plottool as pt
        >>>     pt.show_chipmatch2(rchip1, rchip2, kpts1, kpts2, fm_RAT, fs_RAT, ori=True)
        >>>     num_matches = len(fm_RAT)
        >>>     score_sum = sum(fs_RAT)
        >>>     title = 'Simple matches using the Lowe\'s ratio test'
        >>>     title += '\n num_matches=%r, score_sum=%.2f' % (num_matches, score_sum)
        >>>     pt.set_figtitle(title)
        >>>     pt.show_if_requested()
    """
    import utool as ut
    import vtool as vt
    from vtool import image as gtool
    from vtool import features as feattool
    import pyflann
    # Get params
    ratio_thresh = kwargs.get('ratio_thresh', .625)
    print('ratio_thresh=%r' % (ratio_thresh, ))
    featkw = vt.get_extract_features_default_params()
    ut.updateif_haskey(featkw, kwargs)
    # Read Images
    fpath1 = ut.grab_test_imgpath(fname1)
    fpath2 = ut.grab_test_imgpath(fname2)
    # Extract Features
    kpts1, vecs1 = feattool.extract_features(fpath1, **featkw)
    kpts2, vecs2 = feattool.extract_features(fpath2, **featkw)
    rchip1 = gtool.imread(fpath1)
    rchip2 = gtool.imread(fpath2)

    # Run Algorithm
    def assign_nearest_neighbors(vecs1, vecs2, K=2):
        checks = 800
        flann_params = {'algorithm': 'kdtree', 'trees': 8}
        #pseudo_max_dist_sqrd = (np.sqrt(2) * 512) ** 2
        pseudo_max_dist_sqrd = 2 * (512**2)
        flann = vt.flann_cache(vecs1, flann_params=flann_params)
        try:
            fx2_to_fx1, _fx2_to_dist = flann.nn_index(vecs2,
                                                      num_neighbors=K,
                                                      checks=checks)
        except pyflann.FLANNException:
            print('vecs1.shape = %r' % (vecs1.shape, ))
            print('vecs2.shape = %r' % (vecs2.shape, ))
            print('vecs1.dtype = %r' % (vecs1.dtype, ))
            print('vecs2.dtype = %r' % (vecs2.dtype, ))
            raise
        fx2_to_dist = np.divide(_fx2_to_dist, pseudo_max_dist_sqrd)
        return fx2_to_fx1, fx2_to_dist

    def ratio_test(fx2_to_fx1, fx2_to_dist, ratio_thresh):
        fx2_to_ratio = np.divide(fx2_to_dist.T[0], fx2_to_dist.T[1])
        fx2_to_isvalid = fx2_to_ratio < ratio_thresh
        fx2_m = np.where(fx2_to_isvalid)[0]
        fx1_m = fx2_to_fx1.T[0].take(fx2_m)
        fs_RAT = np.subtract(1.0, fx2_to_ratio.take(fx2_m))
        fm_RAT = np.vstack((fx1_m, fx2_m)).T
        # return normalizer info as well
        fx1_m_normalizer = fx2_to_fx1.T[1].take(fx2_m)
        fm_norm_RAT = np.vstack((fx1_m_normalizer, fx2_m)).T
        return fm_RAT, fs_RAT, fm_norm_RAT

    # GET NEAREST NEIGHBORS
    fx2_to_fx1, fx2_to_dist = assign_nearest_neighbors(vecs1, vecs2, K=2)
    #fx2_m = np.arange(len(fx2_to_fx1))
    #fx1_m = fx2_to_fx1.T[0]
    #fm_ORIG = np.vstack((fx1_m, fx2_m)).T
    #fs_ORIG = fx2_to_dist.T[0]
    #fs_ORIG = 1 - np.divide(fx2_to_dist.T[0], fx2_to_dist.T[1])
    #np.ones(len(fm_ORIG))
    # APPLY RATIO TEST
    #ratio_thresh = .625
    fm_RAT, fs_RAT, fm_norm_RAT = ratio_test(fx2_to_fx1, fx2_to_dist,
                                             ratio_thresh)
    kpts1 = kpts1.astype(np.float64)
    kpts2 = kpts2.astype(np.float64)
    matches_testtup = (kpts1, kpts2, fm_RAT, fs_RAT, rchip1, rchip2)
    return matches_testtup
コード例 #6
0
ファイル: dummy.py プロジェクト: Erotemic/vtool
def testdata_ratio_matches(fname1='easy1.png', fname2='easy2.png', **kwargs):
    r"""
    Runs simple ratio-test matching between two images.
    Technically this is not dummy data.

    Args:
        fname1 (str):
        fname2 (str):

    Returns:
        tuple : matches_testtup

    CommandLine:
        python -m vtool.tests.dummy --test-testdata_ratio_matches
        python -m vtool.tests.dummy --test-testdata_ratio_matches --help
        python -m vtool.tests.dummy --test-testdata_ratio_matches --show
        python -m vtool.tests.dummy --test-testdata_ratio_matches --show --ratio_thresh=1.1 --rotation_invariance

        python -m vtool.tests.dummy --test-testdata_ratio_matches --show --ratio_thresh=.625 --rotation_invariance --fname1 easy1.png --fname2 easy3.png
        python -m vtool.tests.dummy --test-testdata_ratio_matches --show --ratio_thresh=.625 --no-rotation_invariance --fname1 easy1.png --fname2 easy3.png

    Example:
        >>> # ENABLE_DOCTEST
        >>> from vtool.tests.dummy import *  # NOQA
        >>> import vtool as vt
        >>> # build test data
        >>> fname1 = ut.get_argval('--fname1', type_=str, default='easy1.png')
        >>> fname2 = ut.get_argval('--fname2', type_=str, default='easy2.png')
        >>> # execute function
        >>> default_dict = vt.get_extract_features_default_params()
        >>> default_dict['ratio_thresh'] = .625
        >>> kwargs = ut.argparse_dict(default_dict)
        >>> matches_testtup = testdata_ratio_matches(fname1, fname2, **kwargs)
        >>> (kpts1, kpts2, fm_RAT, fs_RAT, rchip1, rchip2) = matches_testtup
        >>> if ut.show_was_requested():
        >>>     import plottool as pt
        >>>     pt.show_chipmatch2(rchip1, rchip2, kpts1, kpts2, fm_RAT, fs_RAT, ori=True)
        >>>     num_matches = len(fm_RAT)
        >>>     score_sum = sum(fs_RAT)
        >>>     title = 'Simple matches using the Lowe\'s ratio test'
        >>>     title += '\n num_matches=%r, score_sum=%.2f' % (num_matches, score_sum)
        >>>     pt.set_figtitle(title)
        >>>     pt.show_if_requested()
    """
    import utool as ut
    import vtool as vt
    from vtool import image as gtool
    from vtool import features as feattool
    import pyflann
    # Get params
    ratio_thresh = kwargs.get('ratio_thresh', .625)
    print('ratio_thresh=%r' % (ratio_thresh,))
    featkw = vt.get_extract_features_default_params()
    ut.updateif_haskey(featkw, kwargs)
    # Read Images
    fpath1 = ut.grab_test_imgpath(fname1)
    fpath2 = ut.grab_test_imgpath(fname2)
    # Extract Features
    kpts1, vecs1 = feattool.extract_features(fpath1, **featkw)
    kpts2, vecs2 = feattool.extract_features(fpath2, **featkw)
    rchip1 = gtool.imread(fpath1)
    rchip2 = gtool.imread(fpath2)
    # Run Algorithm
    def assign_nearest_neighbors(vecs1, vecs2, K=2):
        checks = 800
        flann_params = {
            'algorithm': 'kdtree',
            'trees': 8
        }
        #pseudo_max_dist_sqrd = (np.sqrt(2) * 512) ** 2
        pseudo_max_dist_sqrd = 2 * (512 ** 2)
        flann = vt.flann_cache(vecs1, flann_params=flann_params)
        try:
            fx2_to_fx1, _fx2_to_dist = flann.nn_index(vecs2, num_neighbors=K, checks=checks)
        except pyflann.FLANNException:
            print('vecs1.shape = %r' % (vecs1.shape,))
            print('vecs2.shape = %r' % (vecs2.shape,))
            print('vecs1.dtype = %r' % (vecs1.dtype,))
            print('vecs2.dtype = %r' % (vecs2.dtype,))
            raise
        fx2_to_dist = np.divide(_fx2_to_dist, pseudo_max_dist_sqrd)
        return fx2_to_fx1, fx2_to_dist

    def ratio_test(fx2_to_fx1, fx2_to_dist, ratio_thresh):
        fx2_to_ratio = np.divide(fx2_to_dist.T[0], fx2_to_dist.T[1])
        fx2_to_isvalid = fx2_to_ratio < ratio_thresh
        fx2_m = np.where(fx2_to_isvalid)[0]
        fx1_m = fx2_to_fx1.T[0].take(fx2_m)
        fs_RAT = np.subtract(1.0, fx2_to_ratio.take(fx2_m))
        fm_RAT = np.vstack((fx1_m, fx2_m)).T
        # return normalizer info as well
        fx1_m_normalizer = fx2_to_fx1.T[1].take(fx2_m)
        fm_norm_RAT = np.vstack((fx1_m_normalizer, fx2_m)).T
        return fm_RAT, fs_RAT, fm_norm_RAT

    # GET NEAREST NEIGHBORS
    fx2_to_fx1, fx2_to_dist = assign_nearest_neighbors(vecs1, vecs2, K=2)
    #fx2_m = np.arange(len(fx2_to_fx1))
    #fx1_m = fx2_to_fx1.T[0]
    #fm_ORIG = np.vstack((fx1_m, fx2_m)).T
    #fs_ORIG = fx2_to_dist.T[0]
    #fs_ORIG = 1 - np.divide(fx2_to_dist.T[0], fx2_to_dist.T[1])
    #np.ones(len(fm_ORIG))
    # APPLY RATIO TEST
    #ratio_thresh = .625
    fm_RAT, fs_RAT, fm_norm_RAT = ratio_test(fx2_to_fx1, fx2_to_dist, ratio_thresh)
    kpts1 = kpts1.astype(np.float64)
    kpts2 = kpts2.astype(np.float64)
    matches_testtup = (kpts1, kpts2, fm_RAT, fs_RAT, rchip1, rchip2)
    return matches_testtup