Esempio n. 1
0
    def show_normalizers(match, fnum=None, pnum=None, update=True):
        import plottool as pt
        from plottool import plot_helpers as ph

        # hack keys out of namespace
        keys = ["rchip", "kpts"]
        rchip1, kpts1 = ut.dict_take(match.annot1.__dict__, keys)
        rchip2, kpts2 = ut.dict_take(match.annot2.__dict__, keys)
        fs, fm = match.fs, match.fm_norm
        cmap = "cool"
        draw_lines = True
        if fnum is None:
            fnum = pt.next_fnum()
        pt.figure(fnum=fnum, pnum=pnum)
        # doclf=True, docla=True)
        ax, xywh1, xywh2 = pt.show_chipmatch2(
            rchip1, rchip2, kpts1, kpts2, fm=fm, fs=fs, fnum=fnum, cmap=cmap, draw_lines=draw_lines
        )
        ph.set_plotdat(ax, "viztype", "matches")
        ph.set_plotdat(ax, "key", match.key)
        title = match.key + "\n num=%d, sum=%.2f" % (len(fm), sum(fs))
        pt.set_title(title)
        if update:
            pt.update()
        return ax, xywh1, xywh2
Esempio n. 2
0
 def show_normalizers(match, fnum=None, pnum=None, update=True):
     import plottool as pt
     from plottool import plot_helpers as ph
     # hack keys out of namespace
     keys = ['rchip', 'kpts']
     rchip1, kpts1 = ut.dict_take(match.annot1.__dict__, keys)
     rchip2, kpts2 = ut.dict_take(match.annot2.__dict__, keys)
     fs, fm = match.fs, match.fm_norm
     cmap = 'cool'
     draw_lines = True
     if fnum is None:
         fnum = pt.next_fnum()
     pt.figure(fnum=fnum, pnum=pnum)
     #doclf=True, docla=True)
     ax, xywh1, xywh2 = pt.show_chipmatch2(rchip1,
                                           rchip2,
                                           kpts1,
                                           kpts2,
                                           fm=fm,
                                           fs=fs,
                                           fnum=fnum,
                                           cmap=cmap,
                                           draw_lines=draw_lines)
     ph.set_plotdat(ax, 'viztype', 'matches')
     ph.set_plotdat(ax, 'key', match.key)
     title = match.key + '\n num=%d, sum=%.2f' % (len(fm), sum(fs))
     pt.set_title(title)
     if update:
         pt.update()
     return ax, xywh1, xywh2
Esempio n. 3
0
def show_matches(fm,
                 fs,
                 fnum=1,
                 pnum=None,
                 title='',
                 key=None,
                 simp=None,
                 cmap='hot',
                 draw_lines=True,
                 **locals_):
    #locals_ = locals()
    import plottool as pt
    from plottool import plot_helpers as ph
    # hack keys out of namespace
    keys = 'rchip1, rchip2, kpts1, kpts2'.split(', ')
    rchip1, rchip2, kpts1, kpts2 = ut.dict_take(locals_, keys)
    pt.figure(fnum=fnum, pnum=pnum)
    #doclf=True, docla=True)
    ax, xywh1, xywh2 = pt.show_chipmatch2(rchip1,
                                          rchip2,
                                          kpts1,
                                          kpts2,
                                          fm=fm,
                                          fs=fs,
                                          fnum=fnum,
                                          cmap=cmap,
                                          draw_lines=draw_lines,
                                          ori=True)
    ph.set_plotdat(ax, 'viztype', 'matches')
    ph.set_plotdat(ax, 'simp', simp)
    ph.set_plotdat(ax, 'key', key)
    title = title + '\n num=%d, sum=%.2f' % (len(fm), sum(fs))
    pt.set_title(title)
    return ax, xywh1, xywh2
Esempio n. 4
0
    def chipmatch_view(self, fnum=None, pnum=(1, 1, 1), verbose=None, **kwargs_):
        """
        just visualizes the matches using some type of lines
        """
        import plottool as pt
        from plottool import plot_helpers as ph

        if fnum is None:
            fnum = self.fnum
        if verbose is None:
            verbose = ut.VERBOSE

        if verbose:
            print("-- CHIPMATCH VIEW --")
            print("[ichipmatch_view] self.mode = %r" % (self.mode,))
        mode = kwargs_.get("mode", self.mode)
        draw_ell = mode >= 1
        draw_lines = mode == 2
        if verbose:
            print("[ichipmatch_view] draw_lines = %r" % (draw_lines,))
            print("[ichipmatch_view] draw_ell = %r" % (draw_ell,))
        # pt.figure(fnum=fnum, docla=True, doclf=True)
        # NOTE: i remove the clf here. might cause issues
        pt.figure(fnum=fnum, docla=True, doclf=False)
        # show_matches_kw = self.__dict__.copy()
        show_matches_kw = dict(
            # fnum=fnum, pnum=pnum,
            draw_lines=draw_lines,
            draw_ell=draw_ell,
            colorbar_=True,
            vert=self.vert,
        )
        show_matches_kw.update(kwargs_)

        if verbose:
            print("self.warp_homog = %r" % (self.warp_homog,))
        if self.warp_homog:
            show_matches_kw["H1"] = self.H1
            show_matches_kw["H2"] = self.H2
        if verbose:
            print("show_matches_kw = %s" % (ut.dict_str(show_matches_kw, truncate=True)))

        # tup = show_matches(fm, fs, **show_matches_kw)
        ax, xywh1, xywh2 = pt.show_chipmatch2(
            self.rchip1, self.rchip2, self.kpts1, self.kpts2, fm=self.fm, fs=self.fs, pnum=pnum, **show_matches_kw
        )
        self.xywh2 = xywh2
        ph.set_plotdat(ax, "viztype", "matches")

        if self.truth is not None and self.truth:
            truth_color = pt.TRUE_BLUE  # if  else pt.FALSE_RED
            pt.draw_border(ax, color=truth_color, lw=4)

        if self.title is not None:
            pt.set_title(self.title, ax=ax)
Esempio n. 5
0
    def chipmatch_view(self, fnum=None, pnum=(1, 1, 1), verbose=None, **kwargs_):
        """
        just visualizes the matches using some type of lines
        """
        import plottool as pt
        from plottool import plot_helpers as ph
        if fnum is None:
            fnum     = self.fnum
        if verbose is None:
            verbose = ut.VERBOSE

        if verbose:
            print('-- CHIPMATCH VIEW --')
            print('[ichipmatch_view] self.mode = %r' % (self.mode,))
        mode = kwargs_.get('mode', self.mode)
        draw_ell = mode >= 1
        draw_lines = mode == 2
        if verbose:
            print('[ichipmatch_view] draw_lines = %r' % (draw_lines,))
            print('[ichipmatch_view] draw_ell = %r' % (draw_ell,))
        #pt.figure(fnum=fnum, docla=True, doclf=True)
        # NOTE: i remove the clf here. might cause issues
        pt.figure(fnum=fnum, docla=True, doclf=False)
        #show_matches_kw = self.__dict__.copy()
        show_matches_kw = dict(
            #fnum=fnum, pnum=pnum,
            draw_lines=draw_lines,
            draw_ell=draw_ell,
            colorbar_=True,
            vert=self.vert)
        show_matches_kw.update(kwargs_)

        if verbose:
            print('self.warp_homog = %r' % (self.warp_homog,))
        if self.warp_homog:
            show_matches_kw['H1'] = self.H1
            show_matches_kw['H2'] = self.H2
        if verbose:
            print('show_matches_kw = %s' % (ut.dict_str(show_matches_kw, truncate=True)))

        #tup = show_matches(fm, fs, **show_matches_kw)
        ax, xywh1, xywh2 = pt.show_chipmatch2(
            self.rchip1, self.rchip2,
            self.kpts1, self.kpts2,
            fm=self.fm, fs=self.fs,
            pnum=pnum, **show_matches_kw)
        self.xywh2 = xywh2
        ph.set_plotdat(ax, 'viztype', 'matches')

        if self.truth is not None and self.truth:
            truth_color = pt.TRUE_BLUE  # if  else pt.FALSE_RED
            pt.draw_border(ax, color=truth_color, lw=4)

        if self.title is not None:
            pt.set_title(self.title, ax=ax)
def show_matches(fm, fs, fnum=1, pnum=None, title='', key=None, simp=None,
                 cmap='hot', draw_lines=True, **locals_):
    #locals_ = locals()
    import plottool as pt
    from plottool import plot_helpers as ph
    # hack keys out of namespace
    keys = 'rchip1, rchip2, kpts1, kpts2'.split(', ')
    rchip1, rchip2, kpts1, kpts2 = ut.dict_take(locals_, keys)
    pt.figure(fnum=fnum, pnum=pnum)
    #doclf=True, docla=True)
    ax, xywh1, xywh2 = pt.show_chipmatch2(rchip1, rchip2, kpts1, kpts2, fm=fm,
                                          fs=fs, fnum=fnum, cmap=cmap,
                                          draw_lines=draw_lines, ori=True)
    ph.set_plotdat(ax, 'viztype', 'matches')
    ph.set_plotdat(ax, 'simp', simp)
    ph.set_plotdat(ax, 'key', key)
    title = title + '\n num=%d, sum=%.2f' % (len(fm), sum(fs))
    pt.set_title(title)
    return ax, xywh1, xywh2
Esempio n. 7
0
def show_matches2(ibs,
                  aid1,
                  aid2,
                  fm=None,
                  fs=None,
                  fm_norm=None,
                  sel_fm=[],
                  H1=None,
                  H2=None,
                  qreq_=None,
                  **kwargs):
    """
    TODO: DEPRICATE and use special case of show_name_matches
    Integrate ChipMatch

    Used in:
        Found 1 line(s) in '/home/joncrall/code/ibeis_cnn/ibeis_cnn/ingest_ibeis.py':
        ingest_ibeis.py : 827 |        >>>     ibeis.viz.viz_matches.show_matches2(ibs, aid1, aid2, fm=None, kpts1=kpts1, kpts2=kpts2)
        ----------------------
        Found 4 line(s) in '/home/joncrall/code/ibeis/ibeis/viz/viz_matches.py':
        viz_matches.py : 423 |def show_matches2(ibs, aid1, aid2, fm=None, fs=None, fm_norm=None, sel_fm=[],
        viz_matches.py : 430 |        python -m ibeis.viz.viz_matches --exec-show_matches2 --show
        viz_matches.py : 431 |        python -m ibeis --tf ChipMatch.ishow_single_annotmatch show_matches2 --show
        viz_matches.py : 515 |    return show_matches2(ibs, aid1, aid2, fm, fs, qreq_=qreq_, **kwargs)
        ----------------------
        Found 1 line(s) in '/home/joncrall/code/ibeis/ibeis/viz/interact/interact_matches.py':
        interact_matches.py : 372 |            tup = viz.viz_matches.show_matches2(ibs, self.qaid, self.daid,
        ----------------------
        Found 1 line(s) in '/home/joncrall/code/ibeis/ibeis/algo/hots/vsone_pipeline.py':
        vsone_pipeline.py : 1339 |    viz_matches.show_matches2(ibs, qaid, daid, fm=fm, fs=fs, fm_norm=fm_norm, ori=True,
        ----------------------
        Found 2 line(s) in '/home/joncrall/code/ibeis/ibeis/algo/hots/chip_match.py':
        chip_match.py : 204 |        viz_matches.show_matches2(qreq_.ibs, cm.qaid, daid, qreq_=qreq_,
        chip_match.py : 219 |            ibeis.viz.viz_matches.show_matches2
        ----------------------
        Found 1 line(s) in '/home/joncrall/code/ibeis/ibeis/algo/hots/scoring.py':
        scoring.py : 562 |        viz.viz_matches.show_matches2(qreq_.ibs, qaid, daid, fm, fs,

    CommandLine:
        python -m ibeis.viz.viz_matches --exec-show_matches2 --show
        python -m ibeis --tf ChipMatch.ishow_single_annotmatch show_matches2 --show

    Example:
        >>> # DISABLE_DOCTEST
        >>> from ibeis.algo.hots.chip_match import *  # NOQA
        >>> import ibeis
        >>> cm, qreq_ = ibeis.testdata_cm(defaultdb='PZ_MTEST', default_qaids=[18])
        >>> cm.score_nsum(qreq_)
        >>> daid = cm.get_top_aids()[0]
        >>> cm.show_single_annotmatch(qreq_, daid)
        >>> ut.show_if_requested()
    """
    if qreq_ is None:
        print('[viz_matches] WARNING: qreq_ is None')
    kwargs = kwargs.copy()
    in_image = kwargs.get('in_image', False)
    draw_fmatches = kwargs.pop('draw_fmatches', True)
    # Read query and result info (chips, names, ...)
    rchip1, rchip2, kpts1, kpts2 = _get_annot_pair_info(
        ibs, aid1, aid2, qreq_, draw_fmatches, **kwargs)
    ut.delete_keys(kwargs, ['kpts1', 'kpts2'])
    if fm is None:
        assert len(kpts1) == len(
            kpts2), 'keypoints should be in correspondence'
        import numpy as np
        fm = np.vstack((np.arange(len(kpts1)), np.arange(len(kpts1)))).T

    # Build annotation strings / colors
    lbl1 = 'q' + vh.get_aidstrs(aid1)
    lbl2 = vh.get_aidstrs(aid2)
    if in_image:  # HACK!
        lbl1 = None
        lbl2 = None
    # Draws the chips and keypoint matches
    try:
        ax, xywh1, xywh2 = pt.show_chipmatch2(rchip1,
                                              rchip2,
                                              kpts1,
                                              kpts2,
                                              fm,
                                              fs=fs,
                                              fm_norm=fm_norm,
                                              H1=H1,
                                              H2=H2,
                                              lbl1=lbl1,
                                              lbl2=lbl2,
                                              sel_fm=sel_fm,
                                              **kwargs)
    except Exception as ex:
        ut.printex(ex, 'consider qr.remove_corrupted_queries', '[viz_matches]')
        print('')
        raise
    # Moved the code into show_chipmatch
    #if len(sel_fm) > 0:
    #    # Draw any selected matches
    #    sm_kw = dict(rect=True, colors=pt.BLUE)
    #    pt.plot_fmatch(xywh1, xywh2, kpts1, kpts2, sel_fm, **sm_kw)
    (x1, y1, w1, h1) = xywh1
    (x2, y2, w2, h2) = xywh2
    offset1 = (x1, y1)
    offset2 = (x2, y2)
    annotate_matches2(ibs,
                      aid1,
                      aid2,
                      fm,
                      fs,
                      xywh2=xywh2,
                      xywh1=xywh1,
                      offset1=offset1,
                      offset2=offset2,
                      **kwargs)
    return ax, xywh1, xywh2
Esempio n. 8
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()
Esempio n. 9
0
def show_matches2(ibs, aid1, aid2, fm=None, fs=None, fm_norm=None, sel_fm=[],
                  H1=None, H2=None, qreq_=None, **kwargs):
    """
    TODO: DEPRICATE and use special case of show_name_matches
    Integrate ChipMatch

    Used in:
        Found 1 line(s) in '/home/joncrall/code/ibeis_cnn/ibeis_cnn/ingest_ibeis.py':
        ingest_ibeis.py : 827 |        >>>     ibeis.viz.viz_matches.show_matches2(ibs, aid1, aid2, fm=None, kpts1=kpts1, kpts2=kpts2)
        ----------------------
        Found 4 line(s) in '/home/joncrall/code/ibeis/ibeis/viz/viz_matches.py':
        viz_matches.py : 423 |def show_matches2(ibs, aid1, aid2, fm=None, fs=None, fm_norm=None, sel_fm=[],
        viz_matches.py : 430 |        python -m ibeis.viz.viz_matches --exec-show_matches2 --show
        viz_matches.py : 431 |        python -m ibeis --tf ChipMatch.ishow_single_annotmatch show_matches2 --show
        viz_matches.py : 515 |    return show_matches2(ibs, aid1, aid2, fm, fs, qreq_=qreq_, **kwargs)
        ----------------------
        Found 1 line(s) in '/home/joncrall/code/ibeis/ibeis/viz/interact/interact_matches.py':
        interact_matches.py : 372 |            tup = viz.viz_matches.show_matches2(ibs, self.qaid, self.daid,
        ----------------------
        Found 1 line(s) in '/home/joncrall/code/ibeis/ibeis/algo/hots/vsone_pipeline.py':
        vsone_pipeline.py : 1339 |    viz_matches.show_matches2(ibs, qaid, daid, fm=fm, fs=fs, fm_norm=fm_norm, ori=True,
        ----------------------
        Found 2 line(s) in '/home/joncrall/code/ibeis/ibeis/algo/hots/chip_match.py':
        chip_match.py : 204 |        viz_matches.show_matches2(qreq_.ibs, cm.qaid, daid, qreq_=qreq_,
        chip_match.py : 219 |            ibeis.viz.viz_matches.show_matches2
        ----------------------
        Found 1 line(s) in '/home/joncrall/code/ibeis/ibeis/algo/hots/scoring.py':
        scoring.py : 562 |        viz.viz_matches.show_matches2(qreq_.ibs, qaid, daid, fm, fs,

    CommandLine:
        python -m ibeis.viz.viz_matches --exec-show_matches2 --show
        python -m ibeis --tf ChipMatch.ishow_single_annotmatch show_matches2 --show

    Example:
        >>> # DISABLE_DOCTEST
        >>> from ibeis.algo.hots.chip_match import *  # NOQA
        >>> import ibeis
        >>> cm, qreq_ = ibeis.testdata_cm(defaultdb='PZ_MTEST', default_qaids=[18])
        >>> cm.score_nsum(qreq_)
        >>> daid = cm.get_top_aids()[0]
        >>> cm.show_single_annotmatch(qreq_, daid)
        >>> ut.show_if_requested()
    """
    if qreq_ is None:
        print('[viz_matches] WARNING: qreq_ is None')
    kwargs = kwargs.copy()
    in_image = kwargs.get('in_image', False)
    draw_fmatches = kwargs.pop('draw_fmatches', True)
    # Read query and result info (chips, names, ...)
    rchip1, rchip2, kpts1, kpts2 = _get_annot_pair_info(ibs, aid1, aid2, qreq_,
                                                        draw_fmatches,  **kwargs)
    ut.delete_keys(kwargs, ['kpts1', 'kpts2'])
    if fm is None:
        assert len(kpts1) == len(kpts2), 'keypoints should be in correspondence'
        import numpy as np
        fm = np.vstack((np.arange(len(kpts1)), np.arange(len(kpts1)))).T

    # Build annotation strings / colors
    lbl1 = 'q' + vh.get_aidstrs(aid1)
    lbl2 = vh.get_aidstrs(aid2)
    if in_image:  # HACK!
        lbl1 = None
        lbl2 = None
    # Draws the chips and keypoint matches
    try:
        ax, xywh1, xywh2 = pt.show_chipmatch2(rchip1, rchip2, kpts1, kpts2, fm,
                                               fs=fs, fm_norm=fm_norm,
                                               H1=H1, H2=H2, lbl1=lbl1,
                                              lbl2=lbl2, sel_fm=sel_fm,
                                              **kwargs)
    except Exception as ex:
        ut.printex(ex, 'consider qr.remove_corrupted_queries',
                      '[viz_matches]')
        print('')
        raise
    # Moved the code into show_chipmatch
    #if len(sel_fm) > 0:
    #    # Draw any selected matches
    #    sm_kw = dict(rect=True, colors=pt.BLUE)
    #    pt.plot_fmatch(xywh1, xywh2, kpts1, kpts2, sel_fm, **sm_kw)
    (x1, y1, w1, h1) = xywh1
    (x2, y2, w2, h2) = xywh2
    offset1 = (x1, y1)
    offset2 = (x2, y2)
    annotate_matches2(ibs, aid1, aid2, fm, fs, xywh2=xywh2, xywh1=xywh1,
                      offset1=offset1, offset2=offset2, **kwargs)
    return ax, xywh1, xywh2
Esempio n. 10
0
    def nosql_draw(check_func, rchip1_fpath, rchip2_fpath, kpts1, kpts2):
        # This gets executed in the child thread and does drawing async style
        #from matplotlib.backends.backend_pdf import FigureCanvasPdf as FigureCanvas
        #from matplotlib.backends.backend_pdf import Figure
        #from matplotlib.backends.backend_svg import FigureCanvas
        #from matplotlib.backends.backend_svg import Figure
        from matplotlib.backends.backend_agg import FigureCanvas
        try:
            from matplotlib.backends.backend_agg import Figure
        except ImportError:
            from matplotlib.figure import Figure

        kpts1_ = vt.offset_kpts(kpts1, (0, 0), (resize_factor, resize_factor))
        kpts2_ = vt.offset_kpts(kpts2, (0, 0), (resize_factor, resize_factor))

        #from matplotlib.figure import Figure
        if check_func is not None and check_func():
            return

        rchip1 = vt.imread(rchip1_fpath)
        rchip1 = vt.resize_image_by_scale(rchip1, resize_factor)
        if check_func is not None and check_func():
            return
        rchip2 = vt.imread(rchip2_fpath)
        rchip2 = vt.resize_image_by_scale(rchip2, resize_factor)
        if check_func is not None and check_func():
            return

        try:
            idx = cm.daid2_idx[daid]
            fm   = cm.fm_list[idx]
            fsv  = None if cm.fsv_list is None else cm.fsv_list[idx]
            fs   = None if fsv is None else fsv.prod(axis=1)
        except KeyError:
            fm = []
            fs = None
            fsv = None

        maxnum = 200
        if fs is not None and len(fs) > maxnum:
            # HACK TO ONLY SHOW TOP MATCHES
            sortx = fs.argsort()[::-1]
            fm = fm.take(sortx[:maxnum], axis=0)
            fs = fs.take(sortx[:maxnum], axis=0)

        was_interactive = mpl.is_interactive()
        if was_interactive:
            mpl.interactive(False)
        #fnum = 32
        fig = Figure()
        canvas = FigureCanvas(fig)  # NOQA
        #fig.clf()
        ax = fig.add_subplot(1, 1, 1)
        if check_func is not None and check_func():
            return
        #fig = pt.plt.figure(fnum)
        #H1 = np.eye(3)
        #H2 = np.eye(3)
        #H1[0, 0] = .5
        #H1[1, 1] = .5
        #H2[0, 0] = .5
        #H2[1, 1] = .5
        ax, xywh1, xywh2 = pt.show_chipmatch2(rchip1, rchip2, kpts1_, kpts2_, fm,
                                              fs=fs, colorbar_=False, ax=ax)
        if check_func is not None and check_func():
            return
        savekw = {
            # 'dpi' : 60,
            'dpi' : 80,
        }
        axes_extents = pt.extract_axes_extents(fig)
        #assert len(axes_extents) == 1, 'more than one axes'
        extent = axes_extents[0]
        with io.BytesIO() as stream:
            # This call takes 23% - 15% of the time depending on settings
            fig.savefig(stream, bbox_inches=extent, **savekw)
            stream.seek(0)
            data = np.fromstring(stream.getvalue(), dtype=np.uint8)
        if check_func is not None and check_func():
            return
        pt.plt.close(fig)
        image = cv2.imdecode(data, 1)
        thumbsize = 221
        max_dsize = (thumbsize, thumbsize)
        dsize, sx, sy = vt.resized_clamped_thumb_dims(vt.get_size(image), max_dsize)
        if check_func is not None and check_func():
            return
        image = vt.resize(image, dsize)
        vt.imwrite(fpath, image)
        if check_func is not None and check_func():
            return
Esempio n. 11
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()