Exemplo n.º 1
0
def show_sv_simple(chip1, chip2, kpts1, kpts2, fm, inliers, mx=None, fnum=1, vert=None, **kwargs):
    """

    CommandLine:
        python -m plottool.draw_sv --test-show_sv_simple --show

    Example:
        >>> # DISABLE_DOCTEST
        >>> from plottool.draw_sv import *  # NOQA
        >>> import vtool as vt
        >>> kpts1, kpts2, fm, aff_inliers, chip1, chip2, xy_thresh_sqrd = vt.testdata_matching_affine_inliers()
        >>> inliers = aff_inliers
        >>> mx = None
        >>> fnum = 1
        >>> vert = None  # ut.get_argval('--vert', type_=bool, default=None)
        >>> result = show_sv_simple(chip1, chip2, kpts1, kpts2, fm, inliers, mx, fnum, vert=vert)
        >>> print(result)
        >>> ut.show_if_requested()
    """
    import plottool as pt
    colors = df2.distinct_colors(2, brightness=.95)
    color1, color2 = colors[0:2]
    # Begin the drawing
    fnum = pt.ensure_fnum(fnum)
    df2.figure(fnum=fnum, pnum=(1, 1, 1), docla=True, doclf=True)
    #dmkwargs = dict(fs=None, title='Inconsistent Matches', all_kpts=False, draw_lines=True,
    #                docla=True, draw_border=True, fnum=fnum, pnum=(1, 1, 1), colors=df2.ORANGE)
    inlier_mask = vt.index_to_boolmask(inliers, maxval=len(fm))
    fm_inliers = fm.compress(inlier_mask, axis=0)
    fm_outliers = fm.compress(np.logical_not(inlier_mask), axis=0)
    ax, xywh1, xywh2 = df2.show_chipmatch2(chip1, chip2, vert=vert)
    fmatch_kw = dict(ell_linewidth=2, ell_alpha=.7, line_alpha=.7)
    df2.plot_fmatch(xywh1, xywh2, kpts1, kpts2, fm_inliers, colors=color1, **fmatch_kw)
    df2.plot_fmatch(xywh1, xywh2, kpts1, kpts2, fm_outliers, colors=color2, **fmatch_kw)
Exemplo n.º 2
0
def show_sv_simple(chip1,
                   chip2,
                   kpts1,
                   kpts2,
                   fm,
                   inliers,
                   mx=None,
                   fnum=1,
                   vert=None,
                   **kwargs):
    """

    CommandLine:
        python -m plottool.draw_sv --test-show_sv_simple --show

    Example:
        >>> # DISABLE_DOCTEST
        >>> from plottool.draw_sv import *  # NOQA
        >>> import vtool as vt
        >>> kpts1, kpts2, fm, aff_inliers, chip1, chip2, xy_thresh_sqrd = vt.testdata_matching_affine_inliers()
        >>> inliers = aff_inliers
        >>> mx = None
        >>> fnum = 1
        >>> vert = None  # ut.get_argval('--vert', type_=bool, default=None)
        >>> result = show_sv_simple(chip1, chip2, kpts1, kpts2, fm, inliers, mx, fnum, vert=vert)
        >>> print(result)
        >>> ut.show_if_requested()
    """
    import plottool as pt
    colors = df2.distinct_colors(2, brightness=.95)
    color1, color2 = colors[0:2]
    # Begin the drawing
    fnum = pt.ensure_fnum(fnum)
    df2.figure(fnum=fnum, pnum=(1, 1, 1), docla=True, doclf=True)
    #dmkwargs = dict(fs=None, title='Inconsistent Matches', all_kpts=False, draw_lines=True,
    #                docla=True, draw_border=True, fnum=fnum, pnum=(1, 1, 1), colors=df2.ORANGE)
    inlier_mask = vt.index_to_boolmask(inliers, maxval=len(fm))
    fm_inliers = fm.compress(inlier_mask, axis=0)
    fm_outliers = fm.compress(np.logical_not(inlier_mask), axis=0)
    ax, xywh1, xywh2 = df2.show_chipmatch2(chip1, chip2, vert=vert)
    fmatch_kw = dict(ell_linewidth=2, ell_alpha=.7, line_alpha=.7)
    df2.plot_fmatch(xywh1,
                    xywh2,
                    kpts1,
                    kpts2,
                    fm_inliers,
                    colors=color1,
                    **fmatch_kw)
    df2.plot_fmatch(xywh1,
                    xywh2,
                    kpts1,
                    kpts2,
                    fm_outliers,
                    colors=color2,
                    **fmatch_kw)
Exemplo n.º 3
0
def show_descriptors_match_distances(orgres2_distance, fnum=1, db_name='', **kwargs):
    disttype_list = orgres2_distance.itervalues().next().keys()
    orgtype_list = orgres2_distance.keys()
    (nRow, nCol) = len(orgtype_list), len(disttype_list)
    nColors = nRow * nCol
    color_list = df2.distinct_colors(nColors)
    df2.figure(fnum=fnum, docla=True, doclf=True)
    pnum_ = lambda px: (nRow, nCol, px + 1)
    plot_type = utool.get_arg('--plot-type', default='plot')

    # Remember min and max val for each distance type (l1, emd...)
    distkey2_min = {distkey: np.uint64(-1) for distkey in disttype_list}
    distkey2_max = {distkey: 0 for distkey in disttype_list}

    def _distplot(dists, color, label, distkey, plot_type=plot_type):
        data = sorted(dists)
        ax = df2.gca()
        min_ = distkey2_min[distkey]
        max_ = distkey2_max[distkey]
        if plot_type == 'plot':
            df2.plot(data, color=color, label=label, yscale='linear')
            #xticks = np.linspace(np.min(data), np.max(data), 3)
            #yticks = np.linspace(0, len(data), 5)
            #ax.set_xticks(xticks)
            #ax.set_yticks(yticks)
            ax.set_ylim(min_, max_)
            ax.set_xlim(0, len(dists))
            ax.set_ylabel('distance')
            ax.set_xlabel('matches indexes (sorted by distance)')
            df2.legend(loc='lower right')
        if plot_type == 'pdf':
            df2.plot_pdf(data, color=color, label=label)
            ax.set_ylabel('pr')
            ax.set_xlabel('distance')
            ax.set_xlim(min_, max_)
            df2.legend(loc='upper left')
        df2.dark_background(ax)
        df2.small_xticks(ax)
        df2.small_yticks(ax)

    px = 0
    for orgkey in orgtype_list:
        for distkey in disttype_list:
            dists = orgres2_distance[orgkey][distkey]
            if len(dists) == 0:
                continue
            min_ = dists.min()
            max_ = dists.max()
            distkey2_min[distkey] = min(distkey2_min[distkey], min_)
            distkey2_max[distkey] = max(distkey2_max[distkey], max_)

    for count, orgkey in enumerate(orgtype_list):
        for distkey in disttype_list:
            printDBG('[allres-viz] plotting: %r' % ((orgkey, distkey),))
            dists = orgres2_distance[orgkey][distkey]
            df2.figure(fnum=fnum, pnum=pnum_(px))
            color = color_list[px]
            title = distkey + ' ' + orgkey
            label = 'P(%s | %s)' % (distkey, orgkey)
            _distplot(dists, color, label, distkey, **kwargs)
            if count == 0:
                ax = df2.gca()
                ax.set_title(distkey)
            px += 1

    subtitle = 'the matching distances between sift descriptors'
    title = '(sift) matching distances'
    if db_name != '':
        title = db_name + ' ' + title
    df2.set_figtitle(title, subtitle)
    df2.adjust_subplots_safe()
Exemplo n.º 4
0
def show_sv(chip1,
            chip2,
            kpts1,
            kpts2,
            fm,
            homog_tup=None,
            aff_tup=None,
            mx=None,
            show_assign=True,
            show_lines=True,
            show_kpts=True,
            show_aff=None,
            fnum=1,
            refine_method=None,
            **kwargs):
    """ Visualizes spatial verification

    CommandLine:
        python -m vtool.spatial_verification --test-spatially_verify_kpts --show

    """
    #import plottool as pt
    # GEt Matching chips
    kpts1_m = kpts1[fm.T[0]]
    kpts2_m = kpts2[fm.T[1]]
    wh2 = vt.get_size(chip2)
    #
    # Get Affine Chips, Keypoints, Inliers
    if show_aff is None:
        show_aff_ = aff_tup is not None
    else:
        show_aff_ = show_aff
    if show_aff_:
        (aff_inliers, Aff) = aff_tup
        chip1_At = vt.warpAffine(chip1, Aff, wh2)
        #kpts1_mAt = ktool.transform_kpts(kpts1_m, Aff)
        chip2_blendA = vt.blend_images(chip1_At, chip2)
    #
    # Get Homog Chips, Keypoints, Inliers
    show_homog = homog_tup is not None
    if show_homog:
        (hom_inliers, H) = homog_tup
        #kpts1_mHt = ktool.transform_kpts(kpts1_m, H)
        chip1_Ht = vt.warpHomog(chip1, H, wh2)
        chip2_blendH = vt.blend_images(chip1_Ht, chip2)
    #
    # Drawing settings
    nRows = (show_assign) + (show_aff_) + (show_homog)
    nCols1 = (show_assign) + (show_aff_) + (show_homog)
    nCols2 = 2
    pnum1_ = df2.get_pnum_func(nRows, nCols1)
    pnum2_ = df2.get_pnum_func(nRows, nCols2)
    #in_kwargs  = dict(rect=True,  ell_alpha=.7, eig=False, ori=True, pts=True)
    #out_kwargs = dict(rect=False, ell_alpha=.3, eig=False)
    in_kwargs = dict(rect=False, ell_alpha=.7, eig=False, ori=False, pts=False)
    out_kwargs = dict(rect=False, ell_alpha=.7, eig=False, ori=False)

    def _draw_kpts(*args, **kwargs):
        if not show_kpts:
            return
        df2.draw_kpts2(*args, **kwargs)

    def draw_inlier_kpts(kpts_m, inliers, color, H=None):
        _draw_kpts(kpts_m[inliers], color=color, H=H, **in_kwargs)
        if mx is not None:
            _draw_kpts(kpts_m[mx:(mx + 1)],
                       color=color,
                       ell_linewidth=3,
                       H=H,
                       **in_kwargs)

    def _draw_matches(px, title, inliers):
        dmkwargs = dict(fs=None,
                        title=title,
                        all_kpts=False,
                        draw_lines=True,
                        docla=True,
                        draw_border=True,
                        fnum=fnum,
                        pnum=pnum1_(px),
                        colors=df2.ORANGE)
        __fm = np.vstack((inliers, inliers)).T
        df2.show_chipmatch2(chip1, chip2, kpts1_m, kpts2_m, __fm, **dmkwargs)
        return px + 1

    from plottool import color_funcs
    colors = df2.distinct_colors(2, brightness=.95)
    color1, color2 = colors[0], colors[1]
    color1_dark = color_funcs.darken_rgb(color1, .2)
    color2_dark = color_funcs.darken_rgb(color2, .2)

    def _draw_chip(px, title, chip, inliers, kpts1_m, kpts2_m, H1=None):
        if isinstance(px, tuple):
            pnum = px
            df2.imshow(chip, title=title, fnum=fnum, pnum=pnum)
            px = pnum[2]
        else:
            df2.imshow(chip, title=title, fnum=fnum, pnum=pnum2_(px))
        if kpts1_m is not None:
            _draw_kpts(kpts1_m, color=color1_dark, H=H1, **out_kwargs)
            draw_inlier_kpts(kpts1_m, inliers, color1, H=H1)
        if kpts2_m is not None:
            _draw_kpts(kpts2_m, color=color2_dark, **out_kwargs)
            draw_inlier_kpts(kpts2_m, inliers, color2)
        if kpts2_m is not None and kpts1_m is not None and show_lines:
            __fm = np.vstack((inliers, inliers)).T
            df2.draw_lines2(kpts1_m,
                            kpts2_m,
                            __fm,
                            color_list=[custom_constants.ORANGE],
                            lw=2,
                            line_alpha=1,
                            H1=H1)
        return px + 1

    #
    # Begin the drawing
    df2.figure(fnum=fnum, pnum=(nRows, nCols1, 1), docla=True, doclf=True)
    px = 0
    if show_assign:
        # Draw the Assigned -> Affine -> Homography matches
        px = _draw_matches(px, '%d Assigned matches  ' % len(fm),
                           np.arange(len(fm)))
        if show_aff_:
            px = _draw_matches(px, '%d Initial inliers    ' % len(aff_inliers),
                               aff_inliers)
        if show_homog:
            if refine_method is None:
                refine_method = ''

            if len(refine_method) > 0:
                refine_method_ = '(%s) ' % (refine_method, )
            else:
                refine_method_ = ''
            px = _draw_matches(
                px,
                '%d Refined %sinliers' % (len(hom_inliers), refine_method_),
                hom_inliers)
    #
    # Draw the Affine Transformations
    px = nCols2 * show_assign
    #if show_aff_ or show_homog:

    if show_aff_:
        #px = _draw_chip(px, 'Source',    chip1,        aff_inliers,   kpts1_m, None)
        #px = _draw_chip(px, 'Dest',      chip2,        aff_inliers,   None, kpts2_m)
        px = _draw_chip(px,
                        'Initial Warped',
                        chip1_At,
                        aff_inliers,
                        kpts1_m,
                        None,
                        H1=Aff)
        px = _draw_chip(px,
                        'Initial Blend',
                        chip2_blendA,
                        aff_inliers,
                        kpts1_m,
                        kpts2_m,
                        H1=Aff)
        #px = _draw_chip(px, 'Affine',    chip1_At,     aff_inliers, kpts1_mAt, None)
        #px = _draw_chip(px, 'Aff Blend', chip2_blendA, aff_inliers, kpts1_mAt, kpts2_m)
        pass
    #
    # Draw the Homography Transformation
    if show_homog:
        #px = _draw_chip(px, 'Source',      chip1,        hom_inliers,   kpts1_m, None)
        #px = _draw_chip(px, 'Dest',        chip2,        hom_inliers,   None, kpts2_m)
        #px = _draw_chip(px, 'Homog',       chip1_Ht,     hom_inliers, kpts1_mHt, None)
        #px = _draw_chip(px, 'Homog Blend', chip2_blendH, hom_inliers, kpts1_mHt, kpts2_m)
        px = _draw_chip(px,
                        'Refined Warped',
                        chip1_Ht,
                        hom_inliers,
                        kpts1_m,
                        None,
                        H1=H)
        px = _draw_chip(px,
                        'Refined Blend',
                        chip2_blendH,
                        hom_inliers,
                        kpts1_m,
                        kpts2_m,
                        H1=H)
Exemplo n.º 5
0
def show_qres(ibs, qres, **kwargs):
    """
    Display Query Result Logic
    Defaults to: query chip, groundtruth matches, and top 5 matches
    """
    annote_mode = kwargs.get('annote_mode', 1) % 3  # this is toggled
    figtitle    = kwargs.get('figtitle', '')
    aug         = kwargs.get('aug', '')
    top_aids    = kwargs.get('top_aids', 6)
    gt_aids     = kwargs.get('gt_aids',   [])
    all_kpts    = kwargs.get('all_kpts', False)
    show_query  = kwargs.get('show_query', False)
    in_image    = kwargs.get('in_image', False)
    sidebyside  = kwargs.get('sidebyside', True)
    fnum = df2.kwargs_fnum(kwargs)

    fig = df2.figure(fnum=fnum, docla=True, doclf=True)

    if isinstance(top_aids, int):
        top_aids = qres.get_top_aids(num=top_aids)

    all_gts = ibs.get_annot_groundtruth(qres.qaid)
    nTop   = len(top_aids)
    nSelGt = len(gt_aids)
    nAllGt = len(all_gts)

    max_nCols = 5
    if nTop in [6, 7]:
        max_nCols = 3
    if nTop in [8]:
        max_nCols = 4

    printDBG('[show_qres]========================')
    printDBG('[show_qres]----------------')
    printDBG('[show_qres] #nTop=%r #missed_gts=%r/%r' % (nTop, nSelGt, nAllGt))
    printDBG('[show_qres] * fnum=%r' % (fnum,))
    printDBG('[show_qres] * figtitle=%r' % (figtitle,))
    printDBG('[show_qres] * max_nCols=%r' % (max_nCols,))
    printDBG('[show_qres] * show_query=%r' % (show_query,))
    printDBG('[show_qres] * kwargs=%s' % (utool.dict_str(kwargs),))
    printDBG(qres.get_inspect_str())
    ranked_aids = qres.get_top_aids()
    # Build a subplot grid
    nQuerySubplts = 1 if show_query else 0
    nGtSubplts    = nQuerySubplts + (0 if gt_aids is None else len(gt_aids))
    nTopNSubplts  = nTop
    nTopNCols     = min(max_nCols, nTopNSubplts)
    nGTCols       = min(max_nCols, nGtSubplts)
    nGTCols       = max(nGTCols, nTopNCols)
    nTopNCols     = nGTCols
    nGtRows       = 0 if nGTCols   == 0 else int(np.ceil(nGtSubplts   / nGTCols))
    nTopNRows     = 0 if nTopNCols == 0 else int(np.ceil(nTopNSubplts / nTopNCols))
    nGtCells      = nGtRows * nGTCols
    nRows         = nTopNRows + nGtRows

    # HACK:
    _color_list = df2.distinct_colors(nTop)
    aid2_color = {aid: _color_list[ox] for ox, aid in enumerate(top_aids)}

    # Helpers
    def _show_query_fn(plotx_shift, rowcols):
        """ helper for show_qres """
        plotx = plotx_shift + 1
        pnum = (rowcols[0], rowcols[1], plotx)
        #print('[viz] Plotting Query: pnum=%r' % (pnum,))
        _kwshow = dict(draw_kpts=annote_mode)
        _kwshow.update(kwargs)
        _kwshow['prefix'] = 'q'
        _kwshow['pnum'] = pnum
        _kwshow['aid2_color'] = aid2_color
        _kwshow['draw_ell'] = annote_mode >= 1
        viz_chip.show_chip(ibs, qres.qaid, annote=False, **_kwshow)

    def _plot_matches_aids(aid_list, plotx_shift, rowcols):
        """ helper for show_qres to draw many aids """
        def _show_matches_fn(aid, orank, pnum):
            """ Helper function for drawing matches to one aid """
            aug = 'rank=%r\n' % orank
            #printDBG('[show_qres()] plotting: %r'  % (pnum,))
            _kwshow  = dict(draw_ell=annote_mode, draw_pts=False, draw_lines=annote_mode,
                            ell_alpha=.5, all_kpts=all_kpts)
            _kwshow.update(kwargs)
            _kwshow['fnum'] = fnum
            _kwshow['pnum'] = pnum
            _kwshow['title_aug'] = aug
            # If we already are showing the query dont show it here
            if sidebyside:
                _kwshow['draw_ell'] = annote_mode == 1
                _kwshow['draw_lines'] = annote_mode >= 1
                viz_matches.show_matches(ibs, qres, aid, in_image=in_image, **_kwshow)
            else:
                _kwshow['draw_ell'] = annote_mode >= 1
                if annote_mode == 2:
                    # TODO Find a better name
                    _kwshow['color'] = aid2_color[aid]
                    _kwshow['sel_fx2'] = qres.aid2_fm[aid][:, 1]
                viz_chip.show_chip(ibs, aid, in_image=in_image, annote=False, **_kwshow)
                viz_matches.annotate_matches(ibs, qres, aid, in_image=in_image, show_query=not show_query)

        printDBG('[show_qres()] Plotting Chips %s:' % vh.get_aidstrs(aid_list))
        if aid_list is None:
            return
        # Do lazy load before show
        vh.get_chips(ibs, aid_list, **kwargs)
        vh.get_kpts(ibs, aid_list, **kwargs)
        for ox, aid in enumerate(aid_list):
            plotx = ox + plotx_shift + 1
            pnum = (rowcols[0], rowcols[1], plotx)
            oranks = np.where(ranked_aids == aid)[0]
            if len(oranks) == 0:
                orank = -1
                continue
            orank = oranks[0] + 1
            _show_matches_fn(aid, orank, pnum)

    shift_topN = nGtCells

    if nGtSubplts == 1:
        nGTCols = 1

    if nRows == 0:
        df2.imshow_null(fnum=fnum)
    else:
        fig = df2.figure(fnum=fnum, pnum=(nRows, nGTCols, 1), docla=True, doclf=True)
        #df2.disconnect_callback(fig, 'button_press_event')
        df2.plt.subplot(nRows, nGTCols, 1)
        # Plot Query
        if show_query:
            _show_query_fn(0, (nRows, nGTCols))
        # Plot Ground Truth
        _plot_matches_aids(gt_aids, nQuerySubplts, (nRows, nGTCols))
        _plot_matches_aids(top_aids, shift_topN, (nRows, nTopNCols))
        #figtitle += ' q%s name=%s' % (ibsfuncs.aidstr(qres.qaid), ibs.aid2_name(qres.qaid))
        figtitle += aug
        df2.set_figtitle(figtitle, incanvas=not vh.NO_LBL_OVERRIDE)

    # Result Interaction
    df2.adjust_subplots_safe()
    printDBG('[show_qres()] Finished')
    return fig
Exemplo n.º 6
0
def show_sv(chip1, chip2, kpts1, kpts2, fm, homog_tup=None, aff_tup=None,
            mx=None, show_assign=True, show_lines=True, show_kpts=True,
            show_aff=None, fnum=1, refine_method=None, **kwargs):
    """ Visualizes spatial verification

    CommandLine:
        python -m vtool.spatial_verification --test-spatially_verify_kpts --show

    """
    #import plottool as pt
    # GEt Matching chips
    kpts1_m = kpts1[fm.T[0]]
    kpts2_m = kpts2[fm.T[1]]
    wh2 = vt.get_size(chip2)
    #
    # Get Affine Chips, Keypoints, Inliers
    if show_aff is None:
        show_aff_ = aff_tup is not None
    else:
        show_aff_ = show_aff
    if show_aff_:
        (aff_inliers, Aff) = aff_tup
        chip1_At = vt.warpAffine(chip1, Aff, wh2)
        #kpts1_mAt = ktool.transform_kpts(kpts1_m, Aff)
        chip2_blendA = vt.blend_images(chip1_At, chip2)
    #
    # Get Homog Chips, Keypoints, Inliers
    show_homog = homog_tup is not None
    if show_homog:
        (hom_inliers, H) = homog_tup
        #kpts1_mHt = ktool.transform_kpts(kpts1_m, H)
        chip1_Ht = vt.warpHomog(chip1, H, wh2)
        chip2_blendH = vt.blend_images(chip1_Ht, chip2)
    #
    # Drawing settings
    nRows  = (show_assign) + (show_aff_) + (show_homog)
    nCols1 = (show_assign) + (show_aff_) + (show_homog)
    nCols2 = 2
    pnum1_ = df2.get_pnum_func(nRows, nCols1)
    pnum2_ = df2.get_pnum_func(nRows, nCols2)
    #in_kwargs  = dict(rect=True,  ell_alpha=.7, eig=False, ori=True, pts=True)
    #out_kwargs = dict(rect=False, ell_alpha=.3, eig=False)
    in_kwargs  = dict(rect=False,  ell_alpha=.7, eig=False, ori=False, pts=False)
    out_kwargs = dict(rect=False, ell_alpha=.7, eig=False, ori=False)

    def _draw_kpts(*args, **kwargs):
        if not show_kpts:
            return
        df2.draw_kpts2(*args, **kwargs)

    def draw_inlier_kpts(kpts_m, inliers, color, H=None):
        _draw_kpts(kpts_m[inliers], color=color, H=H, **in_kwargs)
        if mx is not None:
            _draw_kpts(kpts_m[mx:(mx + 1)], color=color, ell_linewidth=3, H=H, **in_kwargs)

    def _draw_matches(px, title, inliers):
        dmkwargs = dict(fs=None, title=title, all_kpts=False, draw_lines=True,
                        docla=True, draw_border=True, fnum=fnum, pnum=pnum1_(px), colors=df2.ORANGE)
        __fm = np.vstack((inliers, inliers)).T
        df2.show_chipmatch2(chip1, chip2, kpts1_m, kpts2_m, __fm, **dmkwargs)
        return px + 1

    from plottool import color_funcs
    colors = df2.distinct_colors(2, brightness=.95)
    color1, color2 = colors[0], colors[1]
    color1_dark = color_funcs.darken_rgb(color1, .2)
    color2_dark = color_funcs.darken_rgb(color2, .2)

    def _draw_chip(px, title, chip, inliers, kpts1_m, kpts2_m, H1=None):
        if isinstance(px, tuple):
            pnum = px
            df2.imshow(chip, title=title, fnum=fnum, pnum=pnum)
            px = pnum[2]
        else:
            df2.imshow(chip, title=title, fnum=fnum, pnum=pnum2_(px))
        if kpts1_m is not None:
            _draw_kpts(kpts1_m, color=color1_dark, H=H1, **out_kwargs)
            draw_inlier_kpts(kpts1_m, inliers, color1, H=H1)
        if kpts2_m is not None:
            _draw_kpts(kpts2_m, color=color2_dark, **out_kwargs)
            draw_inlier_kpts(kpts2_m, inliers, color2)
        if kpts2_m is not None and kpts1_m is not None and show_lines:
            __fm = np.vstack((inliers, inliers)).T
            df2.draw_lines2(kpts1_m, kpts2_m, __fm,
                            color_list=[custom_constants.ORANGE], lw=2,
                            line_alpha=1,
                            H1=H1)
        return px + 1
    #
    # Begin the drawing
    df2.figure(fnum=fnum, pnum=(nRows, nCols1, 1), docla=True, doclf=True)
    px = 0
    if show_assign:
        # Draw the Assigned -> Affine -> Homography matches
        px = _draw_matches(px, '%d Assigned matches  ' % len(fm), np.arange(len(fm)))
        if show_aff_:
            px = _draw_matches(px, '%d Initial inliers    ' % len(aff_inliers), aff_inliers)
        if show_homog:
            if refine_method is None:
                refine_method = ''

            if len(refine_method) > 0:
                refine_method_ = '(%s) ' % (refine_method,)
            else:
                refine_method_ = ''
            px = _draw_matches(
                px,
                '%d Refined %sinliers' % (len(hom_inliers), refine_method_),
                hom_inliers)
    #
    # Draw the Affine Transformations
    px = nCols2 * show_assign
    #if show_aff_ or show_homog:

    if show_aff_:
        #px = _draw_chip(px, 'Source',    chip1,        aff_inliers,   kpts1_m, None)
        #px = _draw_chip(px, 'Dest',      chip2,        aff_inliers,   None, kpts2_m)
        px = _draw_chip(px, 'Initial Warped',  chip1_At,     aff_inliers, kpts1_m, None, H1=Aff)
        px = _draw_chip(px, 'Initial Blend', chip2_blendA, aff_inliers, kpts1_m, kpts2_m, H1=Aff)
        #px = _draw_chip(px, 'Affine',    chip1_At,     aff_inliers, kpts1_mAt, None)
        #px = _draw_chip(px, 'Aff Blend', chip2_blendA, aff_inliers, kpts1_mAt, kpts2_m)
        pass
    #
    # Draw the Homography Transformation
    if show_homog:
        #px = _draw_chip(px, 'Source',      chip1,        hom_inliers,   kpts1_m, None)
        #px = _draw_chip(px, 'Dest',        chip2,        hom_inliers,   None, kpts2_m)
        #px = _draw_chip(px, 'Homog',       chip1_Ht,     hom_inliers, kpts1_mHt, None)
        #px = _draw_chip(px, 'Homog Blend', chip2_blendH, hom_inliers, kpts1_mHt, kpts2_m)
        px = _draw_chip(px, 'Refined Warped',  chip1_Ht,     hom_inliers, kpts1_m, None, H1=H)
        px = _draw_chip(px, 'Refined Blend', chip2_blendH, hom_inliers, kpts1_m, kpts2_m, H1=H)
Exemplo n.º 7
0
def plot_clusters(data, datax2_clusterx, centroids, num_pca_dims=3,
                  whiten=False):
    """ Plots centroids and datapoints. Plots accurately up to 3 dimensions.
    If there are more than 3 dimensions, PCA is used to recude the dimenionality
    to the <num_pca_dims> principal components
    """
    # http://www.janeriksolem.net/2012/03/isomap-with-scikit-learn.html
    from plottool import draw_func2 as df2
    data_dims = data.shape[1]
    show_dims = min(num_pca_dims, data_dims)
    if data_dims != show_dims:
        # we can't physiologically see the data, so look at a projection
        print('[akmeans] Doing PCA')
        from sklearn import decomposition
        pcakw = dict(copy=True, n_components=show_dims, whiten=whiten)
        pca = decomposition.PCA(**pcakw).fit(data)
        pca_data = pca.transform(data)
        pca_clusters = pca.transform(centroids)
        print('[akmeans] ...Finished PCA')
    else:
        # pca is not necessary
        print('[akmeans] No need for PCA')
        pca_data = data
        pca_clusters = centroids
    K = len(centroids)
    print(pca_data.shape)
    # Make a color for each cluster
    colors = np.array(df2.distinct_colors(K, brightness=.95))
    data_x = pca_data[:, 0]
    data_y = pca_data[:, 1]
    data_colors = colors[np.array(datax2_clusterx, dtype=np.int32)]
    clus_x = pca_clusters[:, 0]
    clus_y = pca_clusters[:, 1]
    clus_colors = colors
    # Create a figure
    fig = df2.figure(1, doclf=True, docla=True)
    if show_dims == 2:
        ax = df2.plt.gca()
        df2.plt.scatter(data_x, data_y, s=20,  c=data_colors, marker='o', alpha=.2)
        df2.plt.scatter(clus_x, clus_y, s=500, c=clus_colors, marker='*')
        ax.autoscale(enable=False)
        ax.set_aspect('equal')
        df2.dark_background(ax)
    if show_dims == 3:
        from mpl_toolkits.mplot3d import Axes3D  # NOQA
        ax = fig.add_subplot(111, projection='3d')
        data_z = pca_data[:, 2]
        clus_z = pca_clusters[:, 2]
        ax.scatter(data_x, data_y, data_z, s=20,  c=data_colors, marker='o', alpha=.2)
        ax.scatter(clus_x, clus_y, clus_z, s=500, c=clus_colors, marker='*')
        ax.autoscale(enable=False)
        ax.set_aspect('equal')
        df2.dark_background(ax)
        #ax.set_alpha(.1)
        #ut.embed()
        #ax.set_frame_on(False)
    ax = df2.plt.gca()
    waswhitestr = ' +whitening' * whiten
    titlestr = ('AKmeans: K={K}.'
                'PCA projection {data_dims}D -> {show_dims}D'
                '{waswhitestr}').format(**locals())
    ax.set_title(titlestr)
    return fig
Exemplo n.º 8
0
def show_descriptors_match_distances(orgres2_distance,
                                     fnum=1,
                                     db_name='',
                                     **kwargs):
    disttype_list = orgres2_distance.itervalues().next().keys()
    orgtype_list = orgres2_distance.keys()
    (nRow, nCol) = len(orgtype_list), len(disttype_list)
    nColors = nRow * nCol
    color_list = df2.distinct_colors(nColors)
    df2.figure(fnum=fnum, docla=True, doclf=True)
    pnum_ = lambda px: (nRow, nCol, px + 1)
    plot_type = utool.get_arg('--plot-type', default='plot')

    # Remember min and max val for each distance type (l1, emd...)
    distkey2_min = {distkey: np.uint64(-1) for distkey in disttype_list}
    distkey2_max = {distkey: 0 for distkey in disttype_list}

    def _distplot(dists, color, label, distkey, plot_type=plot_type):
        data = sorted(dists)
        ax = df2.gca()
        min_ = distkey2_min[distkey]
        max_ = distkey2_max[distkey]
        if plot_type == 'plot':
            df2.plot(data, color=color, label=label, yscale='linear')
            #xticks = np.linspace(np.min(data), np.max(data), 3)
            #yticks = np.linspace(0, len(data), 5)
            #ax.set_xticks(xticks)
            #ax.set_yticks(yticks)
            ax.set_ylim(min_, max_)
            ax.set_xlim(0, len(dists))
            ax.set_ylabel('distance')
            ax.set_xlabel('matches indexes (sorted by distance)')
            df2.legend(loc='lower right')
        if plot_type == 'pdf':
            df2.plot_pdf(data, color=color, label=label)
            ax.set_ylabel('pr')
            ax.set_xlabel('distance')
            ax.set_xlim(min_, max_)
            df2.legend(loc='upper left')
        df2.dark_background(ax)
        df2.small_xticks(ax)
        df2.small_yticks(ax)

    px = 0
    for orgkey in orgtype_list:
        for distkey in disttype_list:
            dists = orgres2_distance[orgkey][distkey]
            if len(dists) == 0:
                continue
            min_ = dists.min()
            max_ = dists.max()
            distkey2_min[distkey] = min(distkey2_min[distkey], min_)
            distkey2_max[distkey] = max(distkey2_max[distkey], max_)

    for count, orgkey in enumerate(orgtype_list):
        for distkey in disttype_list:
            printDBG('[allres-viz] plotting: %r' % ((orgkey, distkey), ))
            dists = orgres2_distance[orgkey][distkey]
            df2.figure(fnum=fnum, pnum=pnum_(px))
            color = color_list[px]
            title = distkey + ' ' + orgkey
            label = 'P(%s | %s)' % (distkey, orgkey)
            _distplot(dists, color, label, distkey, **kwargs)
            if count == 0:
                ax = df2.gca()
                ax.set_title(distkey)
            px += 1

    subtitle = 'the matching distances between sift descriptors'
    title = '(sift) matching distances'
    if db_name != '':
        title = db_name + ' ' + title
    df2.set_figtitle(title, subtitle)
    df2.adjust_subplots_safe()
Exemplo n.º 9
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)