Exemplo n.º 1
0
def get_keypoint_stats(ibs):
    """
    kp info
    """
    # from ut import util_latex
    #from hsdev import dev_consistency
    #dev_consistency.check_keypoint_consistency(ibs)
    # Keypoint stats
    #ibs.refresh_features()
    import vtool as vt
    from ibeis.control.IBEISControl import IBEISController
    assert(isinstance(ibs, IBEISController))
    valid_aids = np.array(ibs.get_valid_aids())
    cx2_kpts = ibs.get_annot_kpts(valid_aids)
    #cx2_kpts = ibs.feats.cx2_kpts
    # Check cx2_kpts
    cx2_nFeats = list(map(len, cx2_kpts))
    kpts = np.vstack(cx2_kpts)
    print('[dbinfo] --- LaTeX --- ')
    #_printopts = np.get_printoptions()
    #np.set_printoptions(precision=3)
    scales = vt.get_scales(kpts)
    scales = np.array(sorted(scales))
    tex_scale_stats = util_latex.latex_get_stats(r'kpt scale', scales)
    tex_nKpts       = util_latex.latex_scalar(r'\# kpts', len(kpts))
    tex_kpts_stats  = util_latex.latex_get_stats(r'\# kpts/chip', cx2_nFeats)
    print(tex_nKpts)
    print(tex_kpts_stats)
    print(tex_scale_stats)
    #np.set_printoptions(**_printopts)
    print('[dbinfo] ---/LaTeX --- ')
    return (tex_nKpts, tex_kpts_stats, tex_scale_stats)
Exemplo n.º 2
0
 def print_feat_stats(kpts, vecs):
     assert len(vecs) == len(kpts), 'disagreement'
     print('keypoints and vecs agree')
     flat_kpts = np.vstack(kpts)
     num_kpts = list(map(len, kpts))
     kpt_scale = vt.get_scales(flat_kpts)
     num_kpts_stats = ut.get_stats(num_kpts)
     scale_kpts_stats = ut.get_stats(kpt_scale)
     print('Number of ' + prefix + ' keypoints: ' + ut.repr3(num_kpts_stats, nl=0, precision=2))
     print('Scale of ' + prefix + ' keypoints: ' + ut.repr3(scale_kpts_stats, nl=0, precision=2))
Exemplo n.º 3
0
def warp_patch_onto_kpts(
        kpts, patch, chipshape,
        weights=None,
        out=None,
        cov_scale_factor=.2,
        cov_agg_mode='max',
        cov_remove_shape=False,
        cov_remove_scale=False,
        cov_size_penalty_on=True,
        cov_size_penalty_power=.5,
        cov_size_penalty_frac=.1):
    r"""
    Overlays the source image onto a destination image in each keypoint location

    Args:
        kpts (ndarray[float32_t, ndim=2]):  keypoints
        patch (ndarray): patch to warp (like gaussian)
        chipshape (tuple):
        weights (ndarray): score for every keypoint

    Kwargs:
        cov_scale_factor (float):

    Returns:
        ndarray: mask

    CommandLine:
        python -m vtool.coverage_kpts --test-warp_patch_onto_kpts
        python -m vtool.coverage_kpts --test-warp_patch_onto_kpts --show
        python -m vtool.coverage_kpts --test-warp_patch_onto_kpts --show --hole
        python -m vtool.coverage_kpts --test-warp_patch_onto_kpts --show --square
        python -m vtool.coverage_kpts --test-warp_patch_onto_kpts --show --square --hole

    Example:
        >>> # ENABLE_DOCTEST
        >>> from vtool.coverage_kpts import *  # NOQA
        >>> import vtool as vt
        >>> import pyhesaff
        >>> img_fpath    = ut.grab_test_imgpath('carl.jpg')
        >>> (kpts, vecs) = pyhesaff.detect_feats(img_fpath)
        >>> kpts = kpts[::15]
        >>> chip = vt.imread(img_fpath)
        >>> chipshape = chip.shape
        >>> weights = np.ones(len(kpts))
        >>> cov_scale_factor = 1.0
        >>> srcshape = (19, 19)
        >>> radius = srcshape[0] / 2.0
        >>> sigma = 0.4 * radius
        >>> SQUARE = ut.get_argflag('--square')
        >>> HOLE = ut.get_argflag('--hole')
        >>> if SQUARE:
        >>>     patch = np.ones(srcshape)
        >>> else:
        >>>     patch = ptool.gaussian_patch(shape=srcshape, sigma=sigma) #, norm_01=False)
        >>>     patch = patch / patch.max()
        >>> if HOLE:
        >>>     patch[int(patch.shape[0] / 2), int(patch.shape[1] / 2)] = 0
        >>> # execute function
        >>> dstimg = warp_patch_onto_kpts(kpts, patch, chipshape, weights, cov_scale_factor=cov_scale_factor)
        >>> # verify results
        >>> print('dstimg stats %r' % (ut.get_stats_str(dstimg, axis=None)),)
        >>> print('patch stats %r' % (ut.get_stats_str(patch, axis=None)),)
        >>> #print(patch.sum())
        >>> assert np.all(ut.inbounds(dstimg, 0, 1, eq=True))
        >>> # show results
        >>> ut.quit_if_noshow()
        >>> import plottool as pt
        >>> mask = dstimg
        >>> show_coverage_map(chip, mask, patch, kpts)
        >>> pt.show_if_requested()
    """
    import vtool as vt
    #if len(kpts) == 0:
    #    return None
    chip_scale_h = int(np.ceil(chipshape[0] * cov_scale_factor))
    chip_scale_w = int(np.ceil(chipshape[1] * cov_scale_factor))
    if len(kpts) == 0:
        dstimg =  np.zeros((chip_scale_h, chip_scale_w))
        return dstimg
    if weights is None:
        weights = np.ones(len(kpts))
    dsize = (chip_scale_w, chip_scale_h)
    # Allocate destination image
    patch_shape = patch.shape
    # Scale keypoints into destination image
    # <HACK>
    if cov_remove_shape:
        # disregard affine information in keypoints
        # i still dont understand why we are trying this
        (patch_h, patch_w) = patch_shape
        half_width  = (patch_w / 2.0)  # - .5
        half_height = (patch_h / 2.0)  # - .5
        # Center src image
        T1 = vt.translation_mat3x3(-half_width + .5, -half_height + .5)
        # Scale src to the unit circle
        if not cov_remove_scale:
            S1 = vt.scale_mat3x3(1.0 / half_width, 1.0 / half_height)
        # Transform the source image to the keypoint ellipse
        kpts_T = np.array([vt.translation_mat3x3(x, y) for (x, y) in vt.get_xys(kpts).T])
        if not cov_remove_scale:
            kpts_S = np.array([vt.scale_mat3x3(np.sqrt(scale))
                               for scale in vt.get_scales(kpts).T])
        # Adjust for the requested scale factor
        S2 = vt.scale_mat3x3(cov_scale_factor, cov_scale_factor)
        #perspective_list = [S2.dot(A).dot(S1).dot(T1) for A in invVR_aff2Ds]
        if not cov_remove_scale:
            M_list = reduce(vt.matrix_multiply, (S2, kpts_T, kpts_S, S1, T1))
        else:
            M_list = reduce(vt.matrix_multiply, (S2, kpts_T, T1))
    # </HACK>
    else:
        M_list = ktool.get_transforms_from_patch_image_kpts(kpts, patch_shape,
                                                            cov_scale_factor)
    affmat_list = M_list[:, 0:2, :]
    weight_list = weights
    # For each keypoint warp a gaussian scaled by the feature score into the image
    warped_patch_iter = warped_patch_generator(
        patch, dsize, affmat_list, weight_list,
        cov_size_penalty_on=cov_size_penalty_on,
        cov_size_penalty_power=cov_size_penalty_power,
        cov_size_penalty_frac=cov_size_penalty_frac)
    # Either max or sum
    if cov_agg_mode == 'max':
        dstimg = vt.iter_reduce_ufunc(np.maximum, warped_patch_iter, out=out)
    elif cov_agg_mode == 'sum':
        dstimg = vt.iter_reduce_ufunc(np.add, warped_patch_iter, out=out)
        # HACK FOR SUM: DO NOT DO THIS FOR MAX
        dstimg[dstimg > 1.0] = 1.0
    else:
        raise AssertionError('Unknown cov_agg_mode=%r' % (cov_agg_mode,))
    return dstimg
Exemplo n.º 4
0
 def scale(self):
     return vt.get_scales(self.kparr)
Exemplo n.º 5
0
def get_support_data(qreq_, daid_list):
    """

    CommandLine:
        python -m wbia.algo.hots.neighbor_index get_support_data --show

    Example:
        >>> # xdoctest: +REQUIRES(module:wbia_cnn)
        >>> from wbia.algo.hots.neighbor_index import *  # NOQA
        >>> import wbia
        >>> qreq_ = wbia.testdata_qreq_(defaultdb='PZ_MTEST', p=':fgw_thresh=.9,maxscale_thresh=10', a=':size=2')
        >>> daid_list = qreq_.daids
        >>> tup  = get_support_data(qreq_, daid_list)
        >>> vecs_list, fgws_list, fxs_list = tup
        >>> assert all([np.all(fgws > .9) for fgws in fgws_list])
        >>> result = ('depth_profile = %r' % (ut.depth_profile(tup),))
        >>> print(result)

        depth_profile = [[(128, 128), (174, 128)], [128, 174], [128, 174]]

        I can't figure out why this tests isn't determenistic all the time and
        I can't get it to reproduce non-determenism.

        This could be due to theano.

        depth_profile = [[(39, 128), (22, 128)], [39, 22], [39, 22]]
        depth_profile = [[(35, 128), (24, 128)], [35, 24], [35, 24]]
        depth_profile = [[(34, 128), (31, 128)], [34, 31], [34, 31]]
        depth_profile = [[(83, 128), (129, 128)], [83, 129], [83, 129]]
        depth_profile = [[(13, 128), (104, 128)], [13, 104], [13, 104]]
    """
    config2_ = qreq_.get_internal_data_config2()
    vecs_list = qreq_.ibs.get_annot_vecs(daid_list, config2_=config2_)
    # Create corresponding feature indicies
    fxs_list = [np.arange(len(vecs)) for vecs in vecs_list]
    # <HACK:featweight>
    # hack to get  feature weights. returns None if feature weights are turned
    # off in config settings

    if config2_.minscale_thresh is not None or config2_.maxscale_thresh is not None:
        min_ = -np.inf if config2_.minscale_thresh is None else config2_.minscale_thresh
        max_ = np.inf if config2_.maxscale_thresh is None else config2_.maxscale_thresh
        kpts_list = qreq_.ibs.get_annot_kpts(daid_list, config2_=config2_)
        # kpts_list = vt.ziptake(kpts_list, fxs_list, axis=0)  # not needed for first filter
        scales_list = [vt.get_scales(kpts) for kpts in kpts_list]
        # Remove data under the threshold
        flags_list = [
            np.logical_and(scales >= min_, scales <= max_)
            for scales in scales_list
        ]
        vecs_list = vt.zipcompress(vecs_list, flags_list, axis=0)
        fxs_list = vt.zipcompress(fxs_list, flags_list, axis=0)

    if qreq_.qparams.fg_on:
        # I've found that the call to get_annot_fgweights is different on
        # different machines.  Something must be configured differently.
        fgws_list = qreq_.ibs.get_annot_fgweights(daid_list,
                                                  config2_=config2_,
                                                  ensure=True)
        fgws_list = vt.ziptake(fgws_list, fxs_list, axis=0)
        # assert list(map(len, fgws_list)) == list(map(len, vecs_list)), 'bad corresponding vecs'
        if config2_.fgw_thresh is not None and config2_.fgw_thresh > 0:
            flags_list = [fgws > config2_.fgw_thresh for fgws in fgws_list]
            # Remove data under the threshold
            fgws_list = vt.zipcompress(fgws_list, flags_list, axis=0)
            vecs_list = vt.zipcompress(vecs_list, flags_list, axis=0)
            fxs_list = vt.zipcompress(fxs_list, flags_list, axis=0)
    else:
        fgws_list = None
    # </HACK:featweight>
    return vecs_list, fgws_list, fxs_list
Exemplo n.º 6
0
def test_sver_wrapper():
    """
    Test to ensure cpp and python agree and that cpp is faster

    CommandLine:
        python -m vtool.sver_c_wrapper --test-test_sver_wrapper
        python -m vtool.sver_c_wrapper --test-test_sver_wrapper --rebuild-sver
        python -m vtool.sver_c_wrapper --test-test_sver_wrapper --show
        python -m vtool.sver_c_wrapper --test-test_sver_wrapper --show --dummy
        python -m vtool.sver_c_wrapper --test-test_sver_wrapper --show --fname1=easy1.png --fname2=easy2.png
        python -m vtool.sver_c_wrapper --test-test_sver_wrapper --show --fname1=easy1.png --fname2=hard3.png
        python -m vtool.sver_c_wrapper --test-test_sver_wrapper --show --fname1=carl.jpg --fname2=hard3.png

    Example:
        >>> # ENABLE_DOCTEST
        >>> from vtool.sver_c_wrapper import *  # NOQA
        >>> test_sver_wrapper()

    Ignore:
        %timeit call_python_version(*args)
        %timeit get_affine_inliers_cpp(*args)
    """
    import vtool.spatial_verification as sver
    import vtool.tests.dummy as dummy
    xy_thresh_sqrd    = ktool.KPTS_DTYPE(.4)
    scale_thresh_sqrd = ktool.KPTS_DTYPE(2.0)
    ori_thresh        = ktool.KPTS_DTYPE(TAU / 4.0)
    keys = 'xy_thresh_sqrd, scale_thresh_sqrd, ori_thresh'.split(', ')
    print(ut.dict_str(ut.dict_subset(locals(), keys)))

    def report_errors():
        pass

    if ut.get_argflag('--dummy'):
        testtup = dummy.testdata_dummy_matches()
        (kpts1, kpts2, fm_input, fs_input, rchip1, rchip2) = testtup
        fm_input = fm_input.astype(fm_dtype)
        #fm_input = fm_input[0:10].astype(fm_dtype)
        #fs_input = fs_input[0:10].astype(np.float32)
    else:
        fname1 = ut.get_argval('--fname1', type_=str, default='easy1.png')
        fname2 = ut.get_argval('--fname2', type_=str, default='easy2.png')
        testtup = dummy.testdata_ratio_matches(fname1, fname2)
        (kpts1, kpts2, fm_input, fs_input, rchip1, rchip2) = testtup

    # pack up call to aff hypothesis
    import vtool as vt
    import scipy.stats.mstats
    scales1 = vt.get_scales(kpts1.take(fm_input.T[0], axis=0))
    scales2 = vt.get_scales(kpts2.take(fm_input.T[1], axis=0))
    #fs_input = 1 / scipy.stats.mstats.gmean(np.vstack((scales1, scales2)))
    fs_input = scipy.stats.mstats.gmean(np.vstack((scales1, scales2)))
    print('fs_input = ' + ut.numpy_str(fs_input))
    #fs_input[0:-9] = 0
    #fs_input = np.ones(len(fm_input), dtype=fs_dtype)
    #ut.embed()
    #fs_input = scales1 * scales2
    args = (kpts1, kpts2, fm_input, fs_input, xy_thresh_sqrd, scale_thresh_sqrd, ori_thresh)

    ex_list = []

    try:
        with ut.Indenter('[TEST1] '):
            inlier_tup = vt.compare_implementations(
                sver.get_affine_inliers,
                get_affine_inliers_cpp,
                args, lbl1='py', lbl2='c',
                output_lbl=('aff_inliers_list', 'aff_errors_list', 'Aff_mats')
            )
            out_inliers, out_errors, out_mats = inlier_tup
    except AssertionError as ex:
        ex_list.append(ex)
        raise

    try:
        import functools
        with ut.Indenter('[TEST2] '):
            bestinlier_tup = vt.compare_implementations(
                functools.partial(sver.get_best_affine_inliers, forcepy=True),
                get_best_affine_inliers_cpp,
                args, show_output=True, lbl1='py', lbl2='c',
                output_lbl=('bestinliers', 'besterror', 'bestmat')
            )
            bestinliers, besterror, bestmat = bestinlier_tup
    except AssertionError as ex:
        ex_list.append(ex)
        raise

    if len(ex_list) > 0:
        raise AssertionError('some tests failed. see previous stdout')

    #num_inliers_list = np.array(map(len, out_inliers_c))
    #best_argx = num_inliers_list.argmax()
    ##best_inliers_py = out_inliers_py[best_argx]
    #best_inliers_c = out_inliers_c[best_argx]
    if ut.show_was_requested():
        import plottool as pt
        fm_output = fm_input.take(bestinliers, axis=0)
        fnum = pt.next_fnum()
        pt.figure(fnum=fnum, doclf=True, docla=True)
        pt.show_chipmatch2(rchip1, rchip2, kpts1, kpts2, fm_input, ell_linewidth=5, fnum=fnum, pnum=(2, 1, 1))
        pt.show_chipmatch2(rchip1, rchip2, kpts1, kpts2, fm_output, ell_linewidth=5, fnum=fnum, pnum=(2, 1, 2))
        pt.show_if_requested()
Exemplo n.º 7
0
def warp_patch_onto_kpts(kpts,
                         patch,
                         chipshape,
                         weights=None,
                         out=None,
                         cov_scale_factor=.2,
                         cov_agg_mode='max',
                         cov_remove_shape=False,
                         cov_remove_scale=False,
                         cov_size_penalty_on=True,
                         cov_size_penalty_power=.5,
                         cov_size_penalty_frac=.1):
    r"""
    Overlays the source image onto a destination image in each keypoint location

    Args:
        kpts (ndarray[float32_t, ndim=2]):  keypoints
        patch (ndarray): patch to warp (like gaussian)
        chipshape (tuple):
        weights (ndarray): score for every keypoint

    Kwargs:
        cov_scale_factor (float):

    Returns:
        ndarray: mask

    CommandLine:
        python -m vtool.coverage_kpts --test-warp_patch_onto_kpts
        python -m vtool.coverage_kpts --test-warp_patch_onto_kpts --show
        python -m vtool.coverage_kpts --test-warp_patch_onto_kpts --show --hole
        python -m vtool.coverage_kpts --test-warp_patch_onto_kpts --show --square
        python -m vtool.coverage_kpts --test-warp_patch_onto_kpts --show --square --hole

    Example:
        >>> # ENABLE_DOCTEST
        >>> from vtool.coverage_kpts import *  # NOQA
        >>> import vtool as vt
        >>> import pyhesaff
        >>> img_fpath    = ut.grab_test_imgpath('carl.jpg')
        >>> (kpts, vecs) = pyhesaff.detect_feats(img_fpath)
        >>> kpts = kpts[::15]
        >>> chip = vt.imread(img_fpath)
        >>> chipshape = chip.shape
        >>> weights = np.ones(len(kpts))
        >>> cov_scale_factor = 1.0
        >>> srcshape = (19, 19)
        >>> radius = srcshape[0] / 2.0
        >>> sigma = 0.4 * radius
        >>> SQUARE = ut.get_argflag('--square')
        >>> HOLE = ut.get_argflag('--hole')
        >>> if SQUARE:
        >>>     patch = np.ones(srcshape)
        >>> else:
        >>>     patch = ptool.gaussian_patch(shape=srcshape, sigma=sigma) #, norm_01=False)
        >>>     patch = patch / patch.max()
        >>> if HOLE:
        >>>     patch[int(patch.shape[0] / 2), int(patch.shape[1] / 2)] = 0
        >>> # execute function
        >>> dstimg = warp_patch_onto_kpts(kpts, patch, chipshape, weights, cov_scale_factor=cov_scale_factor)
        >>> # verify results
        >>> print('dstimg stats %r' % (ut.get_stats_str(dstimg, axis=None)),)
        >>> print('patch stats %r' % (ut.get_stats_str(patch, axis=None)),)
        >>> #print(patch.sum())
        >>> assert np.all(ut.inbounds(dstimg, 0, 1, eq=True))
        >>> # show results
        >>> ut.quit_if_noshow()
        >>> import plottool as pt
        >>> mask = dstimg
        >>> show_coverage_map(chip, mask, patch, kpts)
        >>> pt.show_if_requested()
    """
    import vtool as vt
    #if len(kpts) == 0:
    #    return None
    chip_scale_h = int(np.ceil(chipshape[0] * cov_scale_factor))
    chip_scale_w = int(np.ceil(chipshape[1] * cov_scale_factor))
    if len(kpts) == 0:
        dstimg = np.zeros((chip_scale_h, chip_scale_w))
        return dstimg
    if weights is None:
        weights = np.ones(len(kpts))
    dsize = (chip_scale_w, chip_scale_h)
    # Allocate destination image
    patch_shape = patch.shape
    # Scale keypoints into destination image
    # <HACK>
    if cov_remove_shape:
        # disregard affine information in keypoints
        # i still dont understand why we are trying this
        (patch_h, patch_w) = patch_shape
        half_width = (patch_w / 2.0)  # - .5
        half_height = (patch_h / 2.0)  # - .5
        # Center src image
        T1 = vt.translation_mat3x3(-half_width + .5, -half_height + .5)
        # Scale src to the unit circle
        if not cov_remove_scale:
            S1 = vt.scale_mat3x3(1.0 / half_width, 1.0 / half_height)
        # Transform the source image to the keypoint ellipse
        kpts_T = np.array(
            [vt.translation_mat3x3(x, y) for (x, y) in vt.get_xys(kpts).T])
        if not cov_remove_scale:
            kpts_S = np.array([
                vt.scale_mat3x3(np.sqrt(scale))
                for scale in vt.get_scales(kpts).T
            ])
        # Adjust for the requested scale factor
        S2 = vt.scale_mat3x3(cov_scale_factor, cov_scale_factor)
        #perspective_list = [S2.dot(A).dot(S1).dot(T1) for A in invVR_aff2Ds]
        if not cov_remove_scale:
            M_list = reduce(vt.matrix_multiply, (S2, kpts_T, kpts_S, S1, T1))
        else:
            M_list = reduce(vt.matrix_multiply, (S2, kpts_T, T1))
    # </HACK>
    else:
        M_list = ktool.get_transforms_from_patch_image_kpts(
            kpts, patch_shape, cov_scale_factor)
    affmat_list = M_list[:, 0:2, :]
    weight_list = weights
    # For each keypoint warp a gaussian scaled by the feature score into the image
    warped_patch_iter = warped_patch_generator(
        patch,
        dsize,
        affmat_list,
        weight_list,
        cov_size_penalty_on=cov_size_penalty_on,
        cov_size_penalty_power=cov_size_penalty_power,
        cov_size_penalty_frac=cov_size_penalty_frac)
    # Either max or sum
    if cov_agg_mode == 'max':
        dstimg = vt.iter_reduce_ufunc(np.maximum, warped_patch_iter, out=out)
    elif cov_agg_mode == 'sum':
        dstimg = vt.iter_reduce_ufunc(np.add, warped_patch_iter, out=out)
        # HACK FOR SUM: DO NOT DO THIS FOR MAX
        dstimg[dstimg > 1.0] = 1.0
    else:
        raise AssertionError('Unknown cov_agg_mode=%r' % (cov_agg_mode, ))
    return dstimg
Exemplo n.º 8
0
 def scale(self):
     return vt.get_scales(self.kparr)
Exemplo n.º 9
0
def test_sver_wrapper():
    """
    Test to ensure cpp and python agree and that cpp is faster

    CommandLine:
        python -m vtool.sver_c_wrapper --test-test_sver_wrapper
        python -m vtool.sver_c_wrapper --test-test_sver_wrapper --rebuild-sver
        python -m vtool.sver_c_wrapper --test-test_sver_wrapper --show
        python -m vtool.sver_c_wrapper --test-test_sver_wrapper --show --dummy
        python -m vtool.sver_c_wrapper --test-test_sver_wrapper --show --fname1=easy1.png --fname2=easy2.png
        python -m vtool.sver_c_wrapper --test-test_sver_wrapper --show --fname1=easy1.png --fname2=hard3.png
        python -m vtool.sver_c_wrapper --test-test_sver_wrapper --show --fname1=carl.jpg --fname2=hard3.png

    Example:
        >>> # ENABLE_DOCTEST
        >>> from vtool.sver_c_wrapper import *  # NOQA
        >>> test_sver_wrapper()

    Ignore:
        %timeit call_python_version(*args)
        %timeit get_affine_inliers_cpp(*args)
    """
    import vtool.spatial_verification as sver
    import vtool.tests.dummy as dummy
    xy_thresh_sqrd = ktool.KPTS_DTYPE(.4)
    scale_thresh_sqrd = ktool.KPTS_DTYPE(2.0)
    ori_thresh = ktool.KPTS_DTYPE(TAU / 4.0)
    keys = 'xy_thresh_sqrd, scale_thresh_sqrd, ori_thresh'.split(', ')
    print(ut.dict_str(ut.dict_subset(locals(), keys)))

    def report_errors():
        pass

    if ut.get_argflag('--dummy'):
        testtup = dummy.testdata_dummy_matches()
        (kpts1, kpts2, fm_input, fs_input, rchip1, rchip2) = testtup
        fm_input = fm_input.astype(fm_dtype)
        #fm_input = fm_input[0:10].astype(fm_dtype)
        #fs_input = fs_input[0:10].astype(np.float32)
    else:
        fname1 = ut.get_argval('--fname1', type_=str, default='easy1.png')
        fname2 = ut.get_argval('--fname2', type_=str, default='easy2.png')
        testtup = dummy.testdata_ratio_matches(fname1, fname2)
        (kpts1, kpts2, fm_input, fs_input, rchip1, rchip2) = testtup

    # pack up call to aff hypothesis
    import vtool as vt
    import scipy.stats.mstats
    scales1 = vt.get_scales(kpts1.take(fm_input.T[0], axis=0))
    scales2 = vt.get_scales(kpts2.take(fm_input.T[1], axis=0))
    #fs_input = 1 / scipy.stats.mstats.gmean(np.vstack((scales1, scales2)))
    fs_input = scipy.stats.mstats.gmean(np.vstack((scales1, scales2)))
    print('fs_input = ' + ut.numpy_str(fs_input))
    #fs_input[0:-9] = 0
    #fs_input = np.ones(len(fm_input), dtype=fs_dtype)
    #ut.embed()
    #fs_input = scales1 * scales2
    args = (kpts1, kpts2, fm_input, fs_input, xy_thresh_sqrd,
            scale_thresh_sqrd, ori_thresh)

    ex_list = []

    try:
        with ut.Indenter('[TEST1] '):
            inlier_tup = vt.compare_implementations(
                sver.get_affine_inliers,
                get_affine_inliers_cpp,
                args,
                lbl1='py',
                lbl2='c',
                output_lbl=('aff_inliers_list', 'aff_errors_list', 'Aff_mats'))
            out_inliers, out_errors, out_mats = inlier_tup
    except AssertionError as ex:
        ex_list.append(ex)
        raise

    try:
        import functools
        with ut.Indenter('[TEST2] '):
            bestinlier_tup = vt.compare_implementations(
                functools.partial(sver.get_best_affine_inliers, forcepy=True),
                get_best_affine_inliers_cpp,
                args,
                show_output=True,
                lbl1='py',
                lbl2='c',
                output_lbl=('bestinliers', 'besterror', 'bestmat'))
            bestinliers, besterror, bestmat = bestinlier_tup
    except AssertionError as ex:
        ex_list.append(ex)
        raise

    if len(ex_list) > 0:
        raise AssertionError('some tests failed. see previous stdout')

    #num_inliers_list = np.array(map(len, out_inliers_c))
    #best_argx = num_inliers_list.argmax()
    ##best_inliers_py = out_inliers_py[best_argx]
    #best_inliers_c = out_inliers_c[best_argx]
    if ut.show_was_requested():
        import plottool as pt
        fm_output = fm_input.take(bestinliers, axis=0)
        fnum = pt.next_fnum()
        pt.figure(fnum=fnum, doclf=True, docla=True)
        pt.show_chipmatch2(rchip1,
                           rchip2,
                           kpts1,
                           kpts2,
                           fm_input,
                           ell_linewidth=5,
                           fnum=fnum,
                           pnum=(2, 1, 1))
        pt.show_chipmatch2(rchip1,
                           rchip2,
                           kpts1,
                           kpts2,
                           fm_output,
                           ell_linewidth=5,
                           fnum=fnum,
                           pnum=(2, 1, 2))
        pt.show_if_requested()
Exemplo n.º 10
0
def _annotate_kpts(kpts_, sel_fx=None, **kwargs):
    r"""
    Args:
        kpts_ (ndarray): keypoints
        sel_fx (None):

    Keywords:
        color:  3/4-tuple, ndarray, or str

    Returns:
        None

    Example:
        >>> from plottool.viz_keypoints import *  # NOQA
        >>> sel_fx = None
        >>> kpts = np.array([[  92.9246,   17.5453,    7.8103,   -3.4594,   10.8566,    0.    ],
        ...                  [  76.8585,   24.7918,   11.4412,   -3.2634,    9.6287,    0.    ],
        ...                  [ 140.6303,   24.9027,   10.4051,  -10.9452, 10.5991,    0.    ],])

    """
    if len(kpts_) == 0:
        print('len(kpts_) == 0...')
        return
    #color = kwargs.get('color', 'distinct' if sel_fx is None else df2.ORANGE)
    color = kwargs.get('color', 'scale' if sel_fx is None else df2.ORANGE)
    if color == 'distinct':
        # hack for distinct colors
        color = df2.distinct_colors(len(kpts_))  # , randomize=True)
    elif color == 'scale':
        # hack for distinct colors
        import vtool as vt
        #color = df2.scores_to_color(vt.get_scales(kpts_), cmap_='inferno', score_range=(0, 50))
        color = df2.scores_to_color(vt.get_scales(kpts_), cmap_='viridis', score_range=(5, 30), cmap_range=None)
        #df2.distinct_colors(len(kpts_))  # , randomize=True)
    # Keypoint drawing kwargs
    drawkpts_kw = {
        'ell': True,
        'pts': False,
        'ell_alpha': .4,
        'ell_linewidth': 2,
        'ell_color': color,
    }
    drawkpts_kw.update(kwargs)

    # draw all keypoints
    if sel_fx is None:
        df2.draw_kpts2(kpts_, **drawkpts_kw)
    else:
        # dont draw the selected keypoint in this batch
        nonsel_kpts_ = np.vstack((kpts_[0:sel_fx], kpts_[sel_fx + 1:]))
        # Draw selected keypoint
        sel_kpts = kpts_[sel_fx:sel_fx + 1]
        import utool as ut
        if ut.isiterable(color) and ut.isiterable(color[0]):
            # hack for distinct colors
            drawkpts_kw['ell_color'] = color[0:sel_fx] + color[sel_fx + 1:]
        drawkpts_kw
        drawkpts_kw2 = drawkpts_kw.copy()
        drawkpts_kw2.update({
            'ell_color': df2.BLUE,
            'eig':  True,
            'rect': True,
            'ori':  True,
        })
        df2.draw_kpts2(nonsel_kpts_, **drawkpts_kw)
        df2.draw_kpts2(sel_kpts, **drawkpts_kw2)