Exemplo n.º 1
0
def show_nearest_descriptors(hs, qcx, qfx, fnum=None):
    if fnum is None:
        fnum = df2.next_fnum()
    # Inspect the nearest neighbors of a descriptor
    dx2_cx = hs.qdat._data_index.ax2_cx
    dx2_fx = hs.qdat._data_index.ax2_fx
    K      = hs.qdat.cfg.nn_cfg.K
    Knorm  = hs.qdat.cfg.nn_cfg.Knorm
    checks = hs.qdat.cfg.nn_cfg.checks
    flann  = hs.qdat._data_index.flann
    qfx2_desc = hs.get_desc(qcx)[qfx:qfx + 1]

    try:
        (qfx2_dx, qfx2_dist) = flann.nn_index(qfx2_desc, K + Knorm, checks=checks)
        qfx2_cx = dx2_cx[qfx2_dx]
        qfx2_fx = dx2_fx[qfx2_dx]

        def get_extract_tuple(cx, fx, k=-1):
            rchip = hs.get_chip(cx)
            kp    = hs.get_kpts(cx)[fx]
            sift  = hs.get_desc(cx)[fx]
            if k == -1:
                info = '\nquery %s, fx=%r' % (hs.cidstr(cx), fx)
                type_ = 'query'
            elif k < K:
                type_ = 'match'
                info = '\nmatch %s, fx=%r k=%r, dist=%r' % (hs.cidstr(cx), fx, k, qfx2_dist[0, k])
            elif k < Knorm + K:
                type_ = 'norm'
                info = '\nnorm  %s, fx=%r k=%r, dist=%r' % (hs.cidstr(cx), fx, k, qfx2_dist[0, k])
            else:
                raise Exception('[viz] problem k=%r')
            return (rchip, kp, sift, fx, cx, info, type_)

        extracted_list = []
        extracted_list.append(get_extract_tuple(qcx, qfx, -1))
        for k in xrange(K + Knorm):
            tup = get_extract_tuple(qfx2_cx[0, k], qfx2_fx[0, k], k)
            extracted_list.append(tup)
        #print('[viz] K + Knorm = %r' % (K + Knorm))

        # Draw the _select_ith_match plot
        nRows, nCols = len(extracted_list), 3
        # Draw selected feature matches
        prevsift = None
        df2.figure(fnum=fnum, docla=True, doclf=True)
        px = 0  # plot offset
        for (rchip, kp, sift, fx, cx, info, type_) in extracted_list:
            print('[viz] ' + info.replace('\n', ''))
            px = draw_feat_row(rchip, fx, kp, sift, fnum, nRows, nCols, px,
                               prevsift=prevsift, cx=cx, info=info, type_=type_)
            prevsift = sift

        df2.adjust_subplots_safe(hspace=1)

    except Exception as ex:
        print('[viz] Error in show nearest descriptors')
        print(ex)
        raise
Exemplo n.º 2
0
def _show_res(hs, res, **kwargs):
    ''' Displays query chip, groundtruth matches, and top 5 matches'''
    #printDBG('[viz._show_res()] %s ' % helpers.printableVal(locals()))
    #printDBG = print
    in_image = hs.prefs.display_cfg.show_results_in_image
    annote = kwargs.pop('annote', 2)  # this is toggled
    fnum = kwargs.get('fnum', 3)
    figtitle = kwargs.get('figtitle', '')
    topN_cxs = kwargs.get('topN_cxs', [])
    gt_cxs = kwargs.get('gt_cxs', [])
    all_kpts = kwargs.get('all_kpts', False)
    interact = kwargs.get('interact', True)
    show_query = kwargs.get('show_query', False)
    dosquare = kwargs.get('dosquare', False)
    if SHOW_QUERY_OVERRIDE is not None:
        show_query = SHOW_QUERY_OVERRIDE

    max_nCols = 5
    if len(topN_cxs) in [6, 7]:
        max_nCols = 3
    if len(topN_cxs) in [8]:
        max_nCols = 4

    printDBG('========================')
    printDBG('[viz._show_res()]----------------')
    all_gts = hs.get_other_indexed_cxs(res.qcx)
    _tup = tuple(map(len, (topN_cxs, gt_cxs, all_gts)))
    printDBG('[viz._show_res()] #topN=%r #missed_gts=%r/%r' % _tup)
    printDBG('[viz._show_res()] * fnum=%r' % (fnum, ))
    printDBG('[viz._show_res()] * figtitle=%r' % (figtitle, ))
    printDBG('[viz._show_res()] * max_nCols=%r' % (max_nCols, ))
    printDBG('[viz._show_res()] * show_query=%r' % (show_query, ))
    ranked_cxs = res.topN_cxs(hs, N='all')
    # Build a subplot grid
    nQuerySubplts = 1 if show_query else 0
    nGtSubplts = nQuerySubplts + (0 if gt_cxs is None else len(gt_cxs))
    nTopNSubplts = 0 if topN_cxs is None else len(topN_cxs)
    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(len(topN_cxs))
    cx2_color = {cx: _color_list[ox] for ox, cx in enumerate(topN_cxs)}

    if IN_IMAGE_OVERRIDE is not None:
        in_image = IN_IMAGE_OVERRIDE

    # Helpers
    def _show_query_fn(plotx_shift, rowcols):
        'helper for viz._show_res'
        plotx = plotx_shift + 1
        pnum = (rowcols[0], rowcols[1], plotx)
        #print('[viz] Plotting Query: pnum=%r' % (pnum,))
        _kwshow = dict(draw_kpts=annote)
        _kwshow.update(kwargs)
        _kwshow['prefix'] = 'q'
        _kwshow['res'] = res
        _kwshow['pnum'] = pnum
        _kwshow['cx2_color'] = cx2_color
        _kwshow['draw_ell'] = annote >= 1
        #_kwshow['in_image'] = in_image
        show_chip(hs, **_kwshow)
        #if in_image:
        #roi1 = hs.cx2_roi(res.qcx)
        #df2.draw_roi(roi1, bbox_color=df2.ORANGE, label='q' + hs.cidstr(res.qcx))

    def _plot_matches_cxs(cx_list, plotx_shift, rowcols):
        def _show_matches_fn(cx, orank, pnum):
            'Helper function for drawing matches to one cx'
            aug = 'rank=%r\n' % orank
            #printDBG('[viz._show_res()] plotting: %r'  % (pnum,))
            _kwshow = dict(draw_ell=annote,
                           draw_pts=False,
                           draw_lines=annote,
                           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 not show_query:
                _kwshow['draw_ell'] = annote == 1
                _kwshow['draw_lines'] = annote >= 1
                res_show_chipres(res, hs, cx, in_image=in_image, **_kwshow)
            else:
                _kwshow['draw_ell'] = annote >= 1
                if annote == 2:
                    # TODO Find a better name
                    _kwshow['color'] = cx2_color[cx]
                    _kwshow['sel_fx2'] = res.cx2_fm[cx][:, 1]
                show_chip(hs, cx, in_image=in_image, **_kwshow)
                annotate_chipres(hs,
                                 res,
                                 cx,
                                 in_image=in_image,
                                 show_query=not show_query)

        'helper for viz._show_res to draw many cxs'
        #printDBG('[viz._show_res()] Plotting Chips %s:' % hs.cidstr(cx_list))
        if cx_list is None:
            return
        for ox, cx in enumerate(cx_list):
            plotx = ox + plotx_shift + 1
            pnum = (rowcols[0], rowcols[1], plotx)
            oranks = np.where(ranked_cxs == cx)[0]
            if len(oranks) == 0:
                orank = -1
                continue
            orank = oranks[0] + 1
            _show_matches_fn(cx, orank, pnum)

    if dosquare:
        # HACK
        nSubplots = nGtSubplts + nTopNSubplts
        nRows, nCols = get_square_row_cols(nSubplots, 3)
        nTopNCols = nGTCols = nCols
        shift_topN = 1
        printDBG('nRows, nCols = (%r, %r)' % (nRows, nCols))
    else:
        shift_topN = nGtCells

    if nGtSubplts == 1:
        nGTCols = 1

    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_cxs(gt_cxs, nQuerySubplts, (nRows, nGTCols))
    _plot_matches_cxs(topN_cxs, shift_topN, (nRows, nTopNCols))
    figtitle += ' q%s name=%s' % (hs.cidstr(res.qcx), hs.cx2_name(res.qcx))
    df2.set_figtitle(figtitle, incanvas=not NO_LABEL_OVERRIDE)

    # Result Interaction
    if interact:
        printDBG('[viz._show_res()] starting interaction')

        def _ctrlclicked_cx(cx):
            printDBG('ctrl+clicked cx=%r' % cx)
            fnum = FNUMS['special']
            fig = df2.figure(fnum=fnum, docla=True, doclf=True)
            df2.disconnect_callback(fig, 'button_press_event')
            viz_spatial_verification(hs, res.qcx, cx2=cx, fnum=fnum)
            fig.canvas.draw()
            df2.bring_to_front(fig)

        def _clicked_cx(cx):
            printDBG('clicked cx=%r' % cx)
            fnum = FNUMS['inspect']
            res.interact_chipres(hs, cx, fnum=fnum)
            fig = df2.gcf()
            fig.canvas.draw()
            df2.bring_to_front(fig)

        def _clicked_none():
            # Toggle if the click is not in any axis
            printDBG('clicked none')
            #print(kwargs)
            _show_res(hs, res, annote=(annote + 1) % 3, **kwargs)
            fig.canvas.draw()

        def _on_res_click(event):
            'result interaction mpl event callback slot'
            print('[viz] clicked result')
            if event.xdata is None or event.inaxes is None:
                #print('clicked outside axes')
                return _clicked_none()
            ax = event.inaxes
            hs_viewtype = ax.__dict__.get('_hs_viewtype', '')
            printDBG(event.__dict__)
            printDBG('hs_viewtype=%r' % hs_viewtype)
            # Clicked a specific chipres
            if hs_viewtype.find('chipres') == 0:
                cx = ax.__dict__.get('_hs_cx')
                # Ctrl-Click
                key = '' if event.key is None else event.key
                print('key = %r' % key)
                if key.find('control') == 0:
                    print('[viz] result control clicked')
                    return _ctrlclicked_cx(cx)
                # Left-Click
                else:
                    print('[viz] result clicked')
                    return _clicked_cx(cx)

        df2.connect_callback(fig, 'button_press_event', _on_res_click)
    df2.adjust_subplots_safe()
    printDBG('[viz._show_res()] Finished')
    return fig
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 = helpers.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)
            #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 right')
        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 orgkey in orgtype_list:
        for distkey in disttype_list:
            print(((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)
            #ax = df2.gca()
            #ax.set_title(title)
            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 draw():
    df2.adjust_subplots_safe()
    df2.draw()
Exemplo n.º 5
0
def show_nearest_descriptors(hs, qcx, qfx, fnum=None):
    if fnum is None:
        fnum = df2.next_fnum()
    # Inspect the nearest neighbors of a descriptor
    dx2_cx = hs.qdat._data_index.ax2_cx
    dx2_fx = hs.qdat._data_index.ax2_fx
    K = hs.qdat.cfg.nn_cfg.K
    Knorm = hs.qdat.cfg.nn_cfg.Knorm
    checks = hs.qdat.cfg.nn_cfg.checks
    flann = hs.qdat._data_index.flann
    qfx2_desc = hs.get_desc(qcx)[qfx:qfx + 1]

    try:
        (qfx2_dx, qfx2_dist) = flann.nn_index(qfx2_desc,
                                              K + Knorm,
                                              checks=checks)
        qfx2_cx = dx2_cx[qfx2_dx]
        qfx2_fx = dx2_fx[qfx2_dx]

        def get_extract_tuple(cx, fx, k=-1):
            rchip = hs.get_chip(cx)
            kp = hs.get_kpts(cx)[fx]
            sift = hs.get_desc(cx)[fx]
            if k == -1:
                info = '\nquery %s, fx=%r' % (hs.cidstr(cx), fx)
                type_ = 'query'
            elif k < K:
                type_ = 'match'
                info = '\nmatch %s, fx=%r k=%r, dist=%r' % (hs.cidstr(cx), fx,
                                                            k, qfx2_dist[0, k])
            elif k < Knorm + K:
                type_ = 'norm'
                info = '\nnorm  %s, fx=%r k=%r, dist=%r' % (hs.cidstr(cx), fx,
                                                            k, qfx2_dist[0, k])
            else:
                raise Exception('[viz] problem k=%r')
            return (rchip, kp, sift, fx, cx, info, type_)

        extracted_list = []
        extracted_list.append(get_extract_tuple(qcx, qfx, -1))
        for k in xrange(K + Knorm):
            tup = get_extract_tuple(qfx2_cx[0, k], qfx2_fx[0, k], k)
            extracted_list.append(tup)
        #print('[viz] K + Knorm = %r' % (K + Knorm))

        # Draw the _select_ith_match plot
        nRows, nCols = len(extracted_list), 3
        # Draw selected feature matches
        prevsift = None
        df2.figure(fnum=fnum, docla=True, doclf=True)
        px = 0  # plot offset
        for (rchip, kp, sift, fx, cx, info, type_) in extracted_list:
            print('[viz] ' + info.replace('\n', ''))
            px = draw_feat_row(rchip,
                               fx,
                               kp,
                               sift,
                               fnum,
                               nRows,
                               nCols,
                               px,
                               prevsift=prevsift,
                               cx=cx,
                               info=info,
                               type_=type_)
            prevsift = sift

        df2.adjust_subplots_safe(hspace=1)

    except Exception as ex:
        print('[viz] Error in show nearest descriptors')
        print(ex)
        raise
Exemplo n.º 6
0
def _show_res(hs, res, **kwargs):
    ''' Displays query chip, groundtruth matches, and top 5 matches'''
    #printDBG('[viz._show_res()] %s ' % helpers.printableVal(locals()))
    #printDBG = print
    in_image = hs.prefs.display_cfg.show_results_in_image
    annote     = kwargs.pop('annote', 2)  # this is toggled
    fnum       = kwargs.get('fnum', 3)
    figtitle   = kwargs.get('figtitle', '')
    topN_cxs   = kwargs.get('topN_cxs', [])
    gt_cxs     = kwargs.get('gt_cxs',   [])
    all_kpts   = kwargs.get('all_kpts', False)
    interact   = kwargs.get('interact', True)
    show_query = kwargs.get('show_query', False)
    dosquare   = kwargs.get('dosquare', False)
    if SHOW_QUERY_OVERRIDE is not None:
        show_query = SHOW_QUERY_OVERRIDE

    max_nCols = 5
    if len(topN_cxs) in [6, 7]:
        max_nCols = 3
    if len(topN_cxs) in [8]:
        max_nCols = 4

    printDBG('========================')
    printDBG('[viz._show_res()]----------------')
    all_gts = hs.get_other_indexed_cxs(res.qcx)
    _tup = tuple(map(len, (topN_cxs, gt_cxs, all_gts)))
    printDBG('[viz._show_res()] #topN=%r #missed_gts=%r/%r' % _tup)
    printDBG('[viz._show_res()] * fnum=%r' % (fnum,))
    printDBG('[viz._show_res()] * figtitle=%r' % (figtitle,))
    printDBG('[viz._show_res()] * max_nCols=%r' % (max_nCols,))
    printDBG('[viz._show_res()] * show_query=%r' % (show_query,))
    ranked_cxs = res.topN_cxs(hs, N='all')
    # Build a subplot grid
    nQuerySubplts = 1 if show_query else 0
    nGtSubplts    = nQuerySubplts + (0 if gt_cxs is None else len(gt_cxs))
    nTopNSubplts  = 0 if topN_cxs is None else len(topN_cxs)
    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(len(topN_cxs))
    cx2_color = {cx: _color_list[ox] for ox, cx in enumerate(topN_cxs)}

    if IN_IMAGE_OVERRIDE is not None:
        in_image = IN_IMAGE_OVERRIDE

    # Helpers
    def _show_query_fn(plotx_shift, rowcols):
        'helper for viz._show_res'
        plotx = plotx_shift + 1
        pnum = (rowcols[0], rowcols[1], plotx)
        #print('[viz] Plotting Query: pnum=%r' % (pnum,))
        _kwshow = dict(draw_kpts=annote)
        _kwshow.update(kwargs)
        _kwshow['prefix'] = 'q'
        _kwshow['res'] = res
        _kwshow['pnum'] = pnum
        _kwshow['cx2_color'] = cx2_color
        _kwshow['draw_ell'] = annote >= 1
        #_kwshow['in_image'] = in_image
        show_chip(hs, **_kwshow)
        #if in_image:
            #roi1 = hs.cx2_roi(res.qcx)
            #df2.draw_roi(roi1, bbox_color=df2.ORANGE, label='q' + hs.cidstr(res.qcx))

    def _plot_matches_cxs(cx_list, plotx_shift, rowcols):

        def _show_matches_fn(cx, orank, pnum):
            'Helper function for drawing matches to one cx'
            aug = 'rank=%r\n' % orank
            #printDBG('[viz._show_res()] plotting: %r'  % (pnum,))
            _kwshow  = dict(draw_ell=annote, draw_pts=False, draw_lines=annote,
                            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 not show_query:
                _kwshow['draw_ell'] = annote == 1
                _kwshow['draw_lines'] = annote >= 1
                res_show_chipres(res, hs, cx, in_image=in_image, **_kwshow)
            else:
                _kwshow['draw_ell'] = annote >= 1
                if annote == 2:
                    # TODO Find a better name
                    _kwshow['color'] = cx2_color[cx]
                    _kwshow['sel_fx2'] = res.cx2_fm[cx][:, 1]
                show_chip(hs, cx, in_image=in_image, **_kwshow)
                annotate_chipres(hs, res, cx, in_image=in_image, show_query=not show_query)

        'helper for viz._show_res to draw many cxs'
        #printDBG('[viz._show_res()] Plotting Chips %s:' % hs.cidstr(cx_list))
        if cx_list is None:
            return
        for ox, cx in enumerate(cx_list):
            plotx = ox + plotx_shift + 1
            pnum = (rowcols[0], rowcols[1], plotx)
            oranks = np.where(ranked_cxs == cx)[0]
            if len(oranks) == 0:
                orank = -1
                continue
            orank = oranks[0] + 1
            _show_matches_fn(cx, orank, pnum)

    if dosquare:
        # HACK
        nSubplots = nGtSubplts + nTopNSubplts
        nRows, nCols = get_square_row_cols(nSubplots, 3)
        nTopNCols = nGTCols = nCols
        shift_topN = 1
        printDBG('nRows, nCols = (%r, %r)' % (nRows, nCols))
    else:
        shift_topN = nGtCells

    if nGtSubplts == 1:
        nGTCols = 1

    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_cxs(gt_cxs, nQuerySubplts, (nRows, nGTCols))
    _plot_matches_cxs(topN_cxs, shift_topN, (nRows, nTopNCols))
    figtitle += ' q%s name=%s' % (hs.cidstr(res.qcx), hs.cx2_name(res.qcx))
    df2.set_figtitle(figtitle, incanvas=not NO_LABEL_OVERRIDE)

    # Result Interaction
    if interact:
        printDBG('[viz._show_res()] starting interaction')

        def _ctrlclicked_cx(cx):
            printDBG('ctrl+clicked cx=%r' % cx)
            fnum = FNUMS['special']
            fig = df2.figure(fnum=fnum, docla=True, doclf=True)
            df2.disconnect_callback(fig, 'button_press_event')
            viz_spatial_verification(hs, res.qcx, cx2=cx, fnum=fnum)
            fig.canvas.draw()
            df2.bring_to_front(fig)

        def _clicked_cx(cx):
            printDBG('clicked cx=%r' % cx)
            fnum = FNUMS['inspect']
            res.interact_chipres(hs, cx, fnum=fnum)
            fig = df2.gcf()
            fig.canvas.draw()
            df2.bring_to_front(fig)

        def _clicked_none():
            # Toggle if the click is not in any axis
            printDBG('clicked none')
            #print(kwargs)
            _show_res(hs, res, annote=(annote + 1) % 3, **kwargs)
            fig.canvas.draw()

        def _on_res_click(event):
            'result interaction mpl event callback slot'
            print('[viz] clicked result')
            if event.xdata is None or event.inaxes is None:
                #print('clicked outside axes')
                return _clicked_none()
            ax = event.inaxes
            hs_viewtype = ax.__dict__.get('_hs_viewtype', '')
            printDBG(event.__dict__)
            printDBG('hs_viewtype=%r' % hs_viewtype)
            # Clicked a specific chipres
            if hs_viewtype.find('chipres') == 0:
                cx = ax.__dict__.get('_hs_cx')
                # Ctrl-Click
                key = '' if event.key is None else event.key
                print('key = %r' % key)
                if key.find('control') == 0:
                    print('[viz] result control clicked')
                    return _ctrlclicked_cx(cx)
                # Left-Click
                else:
                    print('[viz] result clicked')
                    return _clicked_cx(cx)

        df2.connect_callback(fig, 'button_press_event', _on_res_click)
    df2.adjust_subplots_safe()
    printDBG('[viz._show_res()] Finished')
    return fig
Exemplo n.º 7
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 = helpers.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)
            #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 right')
        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 orgkey in orgtype_list:
        for distkey in disttype_list:
            print(((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)
            #ax = df2.gca()
            #ax.set_title(title)
            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.º 8
0
def draw():
    df2.adjust_subplots_safe()
    df2.draw()