Example #1
0
def show_name(ibs, nid, nid2_aids=None, in_image=True, fnum=0, sel_aids=[], subtitle='',
              annote=False, **kwargs):
    print('[viz] show_name nid=%r' % nid)
    aid_list = ibs.get_name_aids(nid)
    name = ibs.get_name_text((nid,))
    ibsfuncs.ensure_annotation_data(ibs, aid_list, chips=(not in_image or annote), feats=annote)
    print('[viz] show_name=%r aid_list=%r' % (name, aid_list))
    nAids = len(aid_list)
    if nAids > 0:
        nRows, nCols = ph.get_square_row_cols(nAids)
        print('[viz*] r=%r, c=%r' % (nRows, nCols))
        #gs2 = gridspec.GridSpec(nRows, nCols)
        pnum_ = df2.get_pnum_func(nRows, nCols)
        fig = df2.figure(fnum=fnum, pnum=pnum_(0), **kwargs)
        fig.clf()
        # Trigger computation of all chips in parallel
        for px, aid in enumerate(aid_list):
            show_chip(ibs, aid=aid, pnum=pnum_(px), annote=annote, in_image=in_image)
            if aid in sel_aids:
                ax = df2.gca()
                df2.draw_border(ax, df2.GREEN, 4)
            #plot_aid3(ibs, aid)
        if isinstance(nid, np.ndarray):
            nid = nid[0]
        if isinstance(name, np.ndarray):
            name = name[0]
    else:
        df2.imshow_null(fnum=fnum, **kwargs)

    figtitle = 'Name View nid=%r name=%r' % (nid, name)
    df2.set_figtitle(figtitle)
Example #2
0
def annotate_matches(ibs, qres, aid2,
                     offset1=(0, 0),
                     offset2=(0, 0),
                     xywh2=(0, 0, 0, 0),
                     xywh1=(0, 0, 0, 0),
                     **kwargs):
    # TODO Use this function when you clean show_matches
    in_image    = kwargs.get('in_image', False)
    show_query  = kwargs.get('show_query', True)
    draw_border = kwargs.get('draw_border', True)
    draw_lbl    = kwargs.get('draw_lbl', True)

    printDBG('[viz] annotate_matches()')
    aid1 = qres.qaid
    truth = ibs.get_match_truth(aid1, aid2)
    truth_color = vh.get_truth_color(truth)
    # Build title
    title = vh.get_query_text(ibs, qres, aid2, truth, **kwargs)
    # Build xlbl
    ax = df2.gca()
    ph.set_plotdat(ax, 'viztype', 'matches')
    ph.set_plotdat(ax, 'qaid', aid1)
    ph.set_plotdat(ax, 'aid1', aid1)
    ph.set_plotdat(ax, 'aid2', aid2)
    if draw_lbl:
        name1, name2 = ibs.get_annot_names([aid1, aid2])
        lbl1 = repr(name1)  + ' : ' + 'q' + vh.get_aidstrs(aid1)
        lbl2 = repr(name2)  + ' : ' +  vh.get_aidstrs(aid2)
    else:
        lbl1, lbl2 = None, None
    if vh.NO_LBL_OVERRIDE:
        title = ''
    df2.set_title(title, ax)
    # Plot annotations over images
    if in_image:
        bbox1, bbox2 = vh.get_bboxes(ibs, [aid1, aid2], [offset1, offset2])
        theta1, theta2 = ibs.get_annot_thetas([aid1, aid2])
        # HACK!
        if show_query:
            df2.draw_bbox(bbox1, bbox_color=df2.ORANGE, lbl=lbl1, theta=theta1)
        bbox_color2 = truth_color if draw_border else df2.ORANGE
        df2.draw_bbox(bbox2, bbox_color=bbox_color2, lbl=lbl2, theta=theta2)
    else:
        xy, w, h = df2._axis_xy_width_height(ax)
        bbox2 = (xy[0], xy[1], w, h)
        theta2 = 0
        if draw_border:
            df2.draw_border(ax, truth_color, 4, offset=offset2)
        if draw_lbl:
            # Custom user lbl for chips 1 and 2
            (x1, y1, w1, h1) = xywh1
            (x2, y2, w2, h2) = xywh2
            df2.absolute_lbl(x1 + w1, y1, lbl1)
            df2.absolute_lbl(x2 + w2, y2, lbl2)
        # No matches draw a red box
    if aid2 not in qres.aid2_fm or len(qres.aid2_fm[aid2]) == 0:
        if draw_border:
            df2.draw_boxedX(bbox2, theta=theta2)
Example #3
0
def show_multiple_chips(ibs,
                        aid_list,
                        in_image=True,
                        fnum=0,
                        sel_aids=[],
                        subtitle='',
                        annote=False,
                        **kwargs):
    """
    CommandLine:
        python -m ibeis.viz.viz_name --test-show_multiple_chips --show --no-inimage
        python -m ibeis.viz.viz_name --test-show_multiple_chips --show --db NNP_Master3 --aids=6435,9861,137,6563,9167,12547,9332,12598,13285 --no-inimage --notitle
        python -m ibeis.viz.viz_name --test-show_multiple_chips --show --db NNP_Master3 --aids=137,6563,12547,9332,12598,13285 --no-inimage --notitle --adjust=.05
        python -m ibeis.viz.viz_name --test-show_multiple_chips --show --db NNP_Master3 --aids=6563,9332,13285,12598 --no-inimage --notitle --adjust=.05 --rc=1,4
        python -m ibeis.viz.viz_name --test-show_multiple_chips --show --db PZ_Master0 --aids=1288 --no-inimage --notitle --adjust=.05
        python -m ibeis.viz.viz_name --test-show_multiple_chips --show --db PZ_Master0 --aids=4020,4839 --no-inimage --notitle --adjust=.05

        python -m ibeis.viz.viz_name --test-show_multiple_chips --db NNP_Master3 --aids=6524,6540,6571,6751 --no-inimage --notitle --adjust=.05 --diskshow

        python -m ibeis.viz.viz_name --test-show_multiple_chips --db PZ_MTEST -a default:index=0:4 --show
        --aids=1 --doboth --show --no-inimage

        python -m ibeis.viz.viz_name --test-show_multiple_chips --db PZ_MTEST --aids=1 --doboth --show --no-inimage
        python -m ibeis.viz.viz_name --test-show_multiple_chips --db PZ_MTEST --aids=1 --doboth --rc=2,1 --show --no-inimage
        python -m ibeis.viz.viz_name --test-show_multiple_chips --db PZ_MTEST --aids=1 --doboth --rc=2,1 --show --notitle --trydrawline --no-draw_lbls
        python -m ibeis.viz.viz_name --test-show_multiple_chips --db PZ_MTEST --aids=1,2 --doboth  --show --notitle --trydrawline

        python -m ibeis.viz.viz_name --test-show_multiple_chips --db PZ_MTEST --aids=1,2,3,4,5 --doboth --rc=2,5 --show --chrlbl --trydrawline --qualtitle --no-figtitle --notitle
        --doboth
        --doboth --show

        python -m ibeis.viz.viz_name --test-show_multiple_chips --db NNP_Master3 --aids=15419 --doboth --rc=2,1 --show --notitle --trydrawline --no-draw_lbls

    Example:
        >>> # DISABLE_DOCTEST
        >>> from ibeis.viz.viz_name import *  # NOQA
        >>> import ibeis
        >>> ibs, aid_list, in_image = testdata_multichips()
        >>> if True:
        >>>     import matplotlib as mpl
        >>>     from ibeis.scripts.thesis import TMP_RC
        >>>     mpl.rcParams.update(TMP_RC)
        >>> fnum = 0
        >>> sel_aids = []
        >>> subtitle = ''
        >>> annote = False
        >>> fig = show_multiple_chips(ibs, aid_list, in_image, fnum, sel_aids, subtitle, annote)
        >>> ut.quit_if_noshow()
        >>> fig.canvas.draw()
        >>> ut.show_if_requested()
    """
    fnum = pt.ensure_fnum(fnum)
    nAids = len(aid_list)
    if nAids == 0:
        fig = df2.figure(fnum=fnum, pnum=(1, 1, 1), **kwargs)
        df2.imshow_null(fnum=fnum, **kwargs)
        return fig
    # Trigger computation of all chips in parallel
    ibsfuncs.ensure_annotation_data(ibs,
                                    aid_list,
                                    chips=(not in_image or annote),
                                    feats=annote)

    print('[viz_name] * annot_vuuid=%r' %
          ((ibs.get_annot_visual_uuids(aid_list), )))
    print('[viz_name] * aid_list=%r' % ((aid_list, )))

    DOBOTH = ut.get_argflag('--doboth')

    rc = ut.get_argval('--rc', type_=list, default=None)
    if rc is None:
        nRows, nCols = ph.get_square_row_cols(nAids * (2 if DOBOTH else 1))
    else:
        nRows, nCols = rc
    notitle = ut.get_argflag('--notitle')
    draw_lbls = not ut.get_argflag('--no-draw_lbls')
    show_chip_kw = dict(annote=annote,
                        in_image=in_image,
                        notitle=notitle,
                        draw_lbls=draw_lbls)
    #print('[viz_name] * r=%r, c=%r' % (nRows, nCols))
    #gs2 = gridspec.GridSpec(nRows, nCols)
    pnum_ = df2.get_pnum_func(nRows, nCols)
    fig = df2.figure(fnum=fnum, pnum=pnum_(0), **kwargs)
    fig.clf()
    ax_list1 = []
    for px, aid in enumerate(aid_list):
        print('px = %r' % (px, ))
        _fig, _ax1 = viz_chip.show_chip(ibs,
                                        aid=aid,
                                        pnum=pnum_(px),
                                        **show_chip_kw)
        print('other_aids = %r' % (ibs.get_annot_contact_aids(aid), ))
        ax = df2.gca()
        ax_list1.append(_ax1)
        if aid in sel_aids:
            df2.draw_border(ax, df2.GREEN, 4)
        if ut.get_argflag('--chrlbl') and not DOBOTH:
            ax.set_xlabel('(' + chr(ord('a') - 1 + px) + ')')
        elif ut.get_argflag('--numlbl') and not DOBOTH:
            ax.set_xlabel('(' + str(px + 1) + ')')
        #plot_aid3(ibs, aid)

    # HACK to show in image and not in image
    if DOBOTH:
        #ut.embed()
        #ph.get_plotdat_dict(ax_list1[1])
        #ph.get_plotdat_dict(ax_list2[1])
        ax_list2 = []

        show_chip_kw['in_image'] = not show_chip_kw['in_image']
        start = px + 1
        for px, aid in enumerate(aid_list, start=start):
            _fig, _ax2 = viz_chip.show_chip(ibs,
                                            aid=aid,
                                            pnum=pnum_(px),
                                            **show_chip_kw)
            ax = df2.gca()
            ax_list2.append(_ax2)

            if ut.get_argflag('--chrlbl'):
                ax.set_xlabel('(' + chr(ord('a') - start + px) + ')')
            elif ut.get_argflag('--numlbl'):
                ax.set_xlabel('(' + str(px - start + 1) + ')')

            if ut.get_argflag('--qualtitle'):
                qualtext = ibs.get_annot_quality_texts(aid)
                ax.set_title(qualtext)

            if aid in sel_aids:
                df2.draw_border(ax, df2.GREEN, 4)

        if in_image:
            ax_list1, ax_list2 = ax_list2, ax_list1

        if ut.get_argflag('--trydrawline'):
            # Unfinished
            #ut.embed()
            # Draw lines between corresponding axes
            # References:
            # http://stackoverflow.com/questions/17543359/drawing-lines-between-two-plots-in-matplotlib
            import matplotlib as mpl
            import vtool as vt
            # !!!
            #http://matplotlib.org/users/transforms_tutorial.html

            #invTransFigure_fn1 = fig.transFigure.inverted().transform
            #invTransFigure_fn2 = fig.transFigure.inverted().transform
            #print(ax_list1)
            #print(ax_list2)
            assert len(ax_list1) == len(ax_list2)

            for ax1, ax2 in zip(ax_list1, ax_list2):
                #_ = ax1.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
                #bbox1 = (0, 0, _.width * fig.dpi, _.height * fig.dpi)

                # returns in figure coordinates
                #bbox1 = df2.get_axis_bbox(ax=ax1)
                #if bbox1[-1] < 0:
                #    # Weird bug
                #    bbox1 = bbox1[1]
                print('--')
                print('ax1 = %r' % (ax1, ))
                print('ax2 = %r' % (ax2, ))
                chipshape = ph.get_plotdat(ax1, 'chipshape')
                #_bbox1 = ax1.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
                #bbox1 = (0, 0, _bbox1.width * fig.dpi, _bbox1.height * fig.dpi)
                bbox1 = (0, 0, chipshape[1], chipshape[0])

                aid_ = ph.get_plotdat(ax2, 'aid')
                aid_list_ = ph.get_plotdat(ax2, 'aid_list')
                index = aid_list_.index(aid_)
                annotation_bbox_list = ph.get_plotdat(ax2,
                                                      'annotation_bbox_list')
                bbox2 = annotation_bbox_list[index]

                print('bbox1 = %r' % (bbox1, ))
                print('bbox2 = %r' % (bbox2, ))

                vert_list1 = np.array(vt.verts_from_bbox(bbox1))
                vert_list2 = np.array(vt.verts_from_bbox(bbox2))

                print('vert_list1 = %r' % (vert_list1, ))
                print('vert_list2 = %r' % (vert_list2, ))
                #for vx in [0, 1, 2, 3]:
                for vx in [0, 1]:
                    vert1 = vert_list1[vx].tolist()
                    vert2 = vert_list2[vx].tolist()
                    print('  ***')
                    print('  * vert1 = %r' % (vert1, ))
                    print('  * vert2 = %r' % (vert2, ))

                    coordsA = coordsB = 'data'
                    #coords = 'axes points'
                    #'axes fraction'
                    #'axes pixels'
                    #coordsA = 'axes pixels'
                    #coordsB = 'data'
                    #'figure fraction'
                    #'figure pixels'
                    #'figure pixels'
                    #'figure points'
                    #'polar'
                    #'offset points'

                    con = mpl.patches.ConnectionPatch(xyA=vert1,
                                                      xyB=vert2,
                                                      coordsA=coordsA,
                                                      coordsB=coordsB,
                                                      axesA=ax1,
                                                      axesB=ax2,
                                                      linewidth=1,
                                                      color='k')
                    #, arrowstyle="-")

                    #ut.embed()
                    #con.set_zorder(None)
                    ax1.add_artist(con)
                    #ax2.add_artist(con)

                    #ut.embed()

                    #verts2.T[1] -= bbox2[-1]
                    #bottom_left1, bottom_right1 = verts1[1:3].tolist()
                    #bottom_left2, bottom_right2 = verts2[1:3].tolist()

                ##transAxes1 = ax1.transData.inverted()
                #transAxes1_fn = ax1.transData.transform
                #transAxes2_fn = ax2.transData.transform

                #transAxes1_fn = ut.identity
                #transAxes2_fn = ut.identity

                #coord_bl1 = transFigure.transform(transAxes1.transform(bottom_left1))
                #coord_br1 = transFigure.transform(transAxes1.transform(bottom_right1))
                #coord_bl1 = invTransFigure_fn1(transAxes1_fn(bottom_left1))
                #print('bottom_left2 = %r' % (bottom_left2,))
                #coord_bl1 = (5, 5)
                #coord_bl2 = invTransFigure_fn2(transAxes2_fn(bottom_left2))
                #print('coord_bl2 = %r' % (coord_bl2,))

                #coord_br1 = invTransFigure_fn1(transAxes1_fn(bottom_right1))
                #coord_br2 = invTransFigure_fn2(transAxes2_fn(bottom_right2))
                ##print('coord_bl1 = %r' % (coord_bl1,))

                #line_coords1 = np.vstack([coord_bl1, coord_bl2])
                #line_coords2 = np.vstack([coord_br1, coord_br2])
                #print('line_coords1 = %r' % (line_coords1,))

                #line1 = mpl.lines.Line2D((line_coords1[0]), (line_coords1[1]), transform=fig.transFigure)
                #line2 = mpl.lines.Line2D((line_coords2[0]), (line_coords2[1]), transform=fig.transFigure)

                #xs1, ys1 = line_coords1.T
                #xs2, ys2 = line_coords2.T

                #linekw = dict(transform=fig.transFigure)
                #linekw = dict()

                #print('xs1 = %r' % (xs1,))
                #print('ys1 = %r' % (ys1,))

                #line1 = mpl.lines.Line2D(xs1, ys1, **linekw)
                #line2 = mpl.lines.Line2D(xs2, ys2, **linekw)  # NOQA
                #shrinkA=5, shrinkB=5, mutation_scale=20, fc="w")

                #ax2.add_artist(con)

                #fig.lines.append(line1)
                #fig.lines.append(line2)

        pass
    return fig
Example #4
0
def show_multiple_chips(ibs, aid_list, in_image=True, fnum=0, sel_aids=[],
                        subtitle='', annote=False, **kwargs):
    """
    CommandLine:
        python -m ibeis.viz.viz_name --test-show_multiple_chips --show --no-inimage
        python -m ibeis.viz.viz_name --test-show_multiple_chips --show --db NNP_Master3 --aids=6435,9861,137,6563,9167,12547,9332,12598,13285 --no-inimage --notitle
        python -m ibeis.viz.viz_name --test-show_multiple_chips --show --db NNP_Master3 --aids=137,6563,12547,9332,12598,13285 --no-inimage --notitle --adjust=.05
        python -m ibeis.viz.viz_name --test-show_multiple_chips --show --db NNP_Master3 --aids=6563,9332,13285,12598 --no-inimage --notitle --adjust=.05 --rc=1,4
        python -m ibeis.viz.viz_name --test-show_multiple_chips --show --db PZ_Master0 --aids=1288 --no-inimage --notitle --adjust=.05
        python -m ibeis.viz.viz_name --test-show_multiple_chips --show --db PZ_Master0 --aids=4020,4839 --no-inimage --notitle --adjust=.05

        python -m ibeis.viz.viz_name --test-show_multiple_chips --db NNP_Master3 --aids=6524,6540,6571,6751 --no-inimage --notitle --adjust=.05 --diskshow

        python -m ibeis.viz.viz_name --test-show_multiple_chips --db PZ_MTEST -a default:index=0:4 --show
        --aids=1 --doboth --show --no-inimage

        python -m ibeis.viz.viz_name --test-show_multiple_chips --db PZ_MTEST --aids=1 --doboth --show --no-inimage
        python -m ibeis.viz.viz_name --test-show_multiple_chips --db PZ_MTEST --aids=1 --doboth --rc=2,1 --show --no-inimage
        python -m ibeis.viz.viz_name --test-show_multiple_chips --db PZ_MTEST --aids=1 --doboth --rc=2,1 --show --notitle --trydrawline --no-draw_lbls
        python -m ibeis.viz.viz_name --test-show_multiple_chips --db PZ_MTEST --aids=1,2 --doboth  --show --notitle --trydrawline

        python -m ibeis.viz.viz_name --test-show_multiple_chips --db PZ_MTEST --aids=1,2,3,4,5 --doboth --rc=2,5 --show --chrlbl --trydrawline --qualtitle --no-figtitle --notitle
        --doboth
        --doboth --show

        python -m ibeis.viz.viz_name --test-show_multiple_chips --db NNP_Master3 --aids=15419 --doboth --rc=2,1 --show --notitle --trydrawline --no-draw_lbls

    Example:
        >>> # DISABLE_DOCTEST
        >>> from ibeis.viz.viz_name import *  # NOQA
        >>> import ibeis
        >>> ibs, aid_list, in_image = testdata_multichips()
        >>> fnum = 0
        >>> sel_aids = []
        >>> subtitle = ''
        >>> annote = False
        >>> fig = show_multiple_chips(ibs, aid_list, in_image, fnum, sel_aids, subtitle, annote)
        >>> ut.quit_if_noshow()
        >>> fig.canvas.draw()
        >>> ut.show_if_requested()
    """
    fnum = pt.ensure_fnum(fnum)
    nAids = len(aid_list)
    if nAids == 0:
        fig = df2.figure(fnum=fnum, pnum=(1, 1, 1), **kwargs)
        df2.imshow_null(fnum=fnum, **kwargs)
        return fig
    # Trigger computation of all chips in parallel
    ibsfuncs.ensure_annotation_data(ibs, aid_list, chips=(not in_image or annote), feats=annote)

    print('[viz_name] * annot_vuuid=%r' % ((ibs.get_annot_visual_uuids(aid_list),)))
    print('[viz_name] * aid_list=%r' % ((aid_list,)))

    DOBOTH = ut.get_argflag('--doboth')

    rc = ut.get_argval('--rc', type_=list, default=None)
    if rc is None:
        nRows, nCols = ph.get_square_row_cols(nAids * (2 if DOBOTH else 1))
    else:
        nRows, nCols = rc
    notitle = ut.get_argflag('--notitle')
    draw_lbls = not ut.get_argflag('--no-draw_lbls')
    show_chip_kw = dict(annote=annote, in_image=in_image, notitle=notitle, draw_lbls=draw_lbls)
    #print('[viz_name] * r=%r, c=%r' % (nRows, nCols))
    #gs2 = gridspec.GridSpec(nRows, nCols)
    pnum_ = df2.get_pnum_func(nRows, nCols)
    fig = df2.figure(fnum=fnum, pnum=pnum_(0), **kwargs)
    fig.clf()
    ax_list1 = []
    for px, aid in enumerate(aid_list):
        print('px = %r' % (px,))
        _fig, _ax1 = viz_chip.show_chip(ibs, aid=aid, pnum=pnum_(px), **show_chip_kw)
        print('other_aids = %r' % (ibs.get_annot_contact_aids(aid),))
        ax = df2.gca()
        ax_list1.append(_ax1)
        if aid in sel_aids:
            df2.draw_border(ax, df2.GREEN, 4)
        if ut.get_argflag('--chrlbl') and not DOBOTH:
            ax.set_xlabel('(' + chr(ord('a') - 1 + px) + ')')
        elif ut.get_argflag('--numlbl') and not DOBOTH:
            ax.set_xlabel('(' + str(px + 1) + ')')
        #plot_aid3(ibs, aid)

    # HACK to show in image and not in image
    if DOBOTH:
        #ut.embed()
        #ph.get_plotdat_dict(ax_list1[1])
        #ph.get_plotdat_dict(ax_list2[1])
        ax_list2 = []

        show_chip_kw['in_image'] = not show_chip_kw['in_image']
        start = px + 1
        for px, aid in enumerate(aid_list, start=start):
            _fig, _ax2 = viz_chip.show_chip(ibs, aid=aid, pnum=pnum_(px), **show_chip_kw)
            ax = df2.gca()
            ax_list2.append(_ax2)

            if ut.get_argflag('--chrlbl'):
                ax.set_xlabel('(' + chr(ord('a') - start + px) + ')')
            elif ut.get_argflag('--numlbl'):
                ax.set_xlabel('(' + str(px - start + 1) + ')')

            if ut.get_argflag('--qualtitle'):
                qualtext = ibs.get_annot_quality_texts(aid)
                ax.set_title(qualtext)

            if aid in sel_aids:
                df2.draw_border(ax, df2.GREEN, 4)

        if in_image:
            ax_list1, ax_list2 = ax_list2, ax_list1

        if ut.get_argflag('--trydrawline'):
            # Unfinished
            #ut.embed()
            # Draw lines between corresponding axes
            # References:
            # http://stackoverflow.com/questions/17543359/drawing-lines-between-two-plots-in-matplotlib
            import matplotlib as mpl
            import vtool as vt
            # !!!
            #http://matplotlib.org/users/transforms_tutorial.html

            #invTransFigure_fn1 = fig.transFigure.inverted().transform
            #invTransFigure_fn2 = fig.transFigure.inverted().transform
            #print(ax_list1)
            #print(ax_list2)
            assert len(ax_list1) == len(ax_list2)

            for ax1, ax2 in zip(ax_list1, ax_list2):
                #_ = ax1.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
                #bbox1 = (0, 0, _.width * fig.dpi, _.height * fig.dpi)

                # returns in figure coordinates
                #bbox1 = df2.get_axis_bbox(ax=ax1)
                #if bbox1[-1] < 0:
                #    # Weird bug
                #    bbox1 = bbox1[1]
                print('--')
                print('ax1 = %r' % (ax1,))
                print('ax2 = %r' % (ax2,))
                chipshape = ph.get_plotdat(ax1, 'chipshape')
                #_bbox1 = ax1.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
                #bbox1 = (0, 0, _bbox1.width * fig.dpi, _bbox1.height * fig.dpi)
                bbox1 = (0, 0, chipshape[1], chipshape[0])

                aid_ = ph.get_plotdat(ax2, 'aid')
                aid_list_ = ph.get_plotdat(ax2, 'aid_list')
                index = aid_list_.index(aid_)
                annotation_bbox_list = ph.get_plotdat(ax2, 'annotation_bbox_list')
                bbox2 = annotation_bbox_list[index]

                print('bbox1 = %r' % (bbox1,))
                print('bbox2 = %r' % (bbox2,))

                vert_list1 = np.array(vt.verts_from_bbox(bbox1))
                vert_list2 = np.array(vt.verts_from_bbox(bbox2))

                print('vert_list1 = %r' % (vert_list1,))
                print('vert_list2 = %r' % (vert_list2,))
                #for vx in [0, 1, 2, 3]:
                for vx in [0, 1]:
                    vert1 = vert_list1[vx].tolist()
                    vert2 = vert_list2[vx].tolist()
                    print('  ***')
                    print('  * vert1 = %r' % (vert1,))
                    print('  * vert2 = %r' % (vert2,))

                    coordsA = coordsB = 'data'
                    #coords = 'axes points'
                    #'axes fraction'
                    #'axes pixels'
                    #coordsA = 'axes pixels'
                    #coordsB = 'data'
                    #'figure fraction'
                    #'figure pixels'
                    #'figure pixels'
                    #'figure points'
                    #'polar'
                    #'offset points'

                    con = mpl.patches.ConnectionPatch(
                        xyA=vert1, xyB=vert2, coordsA=coordsA,
                        coordsB=coordsB,
                        axesA=ax1, axesB=ax2,
                        linewidth=1, color='k')
                    #, arrowstyle="-")

                    #ut.embed()
                    #con.set_zorder(None)
                    ax1.add_artist(con)
                    #ax2.add_artist(con)

                    #ut.embed()

                    #verts2.T[1] -= bbox2[-1]
                    #bottom_left1, bottom_right1 = verts1[1:3].tolist()
                    #bottom_left2, bottom_right2 = verts2[1:3].tolist()

                ##transAxes1 = ax1.transData.inverted()
                #transAxes1_fn = ax1.transData.transform
                #transAxes2_fn = ax2.transData.transform

                #transAxes1_fn = ut.identity
                #transAxes2_fn = ut.identity

                #coord_bl1 = transFigure.transform(transAxes1.transform(bottom_left1))
                #coord_br1 = transFigure.transform(transAxes1.transform(bottom_right1))
                #coord_bl1 = invTransFigure_fn1(transAxes1_fn(bottom_left1))
                #print('bottom_left2 = %r' % (bottom_left2,))
                #coord_bl1 = (5, 5)
                #coord_bl2 = invTransFigure_fn2(transAxes2_fn(bottom_left2))
                #print('coord_bl2 = %r' % (coord_bl2,))

                #coord_br1 = invTransFigure_fn1(transAxes1_fn(bottom_right1))
                #coord_br2 = invTransFigure_fn2(transAxes2_fn(bottom_right2))
                ##print('coord_bl1 = %r' % (coord_bl1,))

                #line_coords1 = np.vstack([coord_bl1, coord_bl2])
                #line_coords2 = np.vstack([coord_br1, coord_br2])
                #print('line_coords1 = %r' % (line_coords1,))

                #line1 = mpl.lines.Line2D((line_coords1[0]), (line_coords1[1]), transform=fig.transFigure)
                #line2 = mpl.lines.Line2D((line_coords2[0]), (line_coords2[1]), transform=fig.transFigure)

                #xs1, ys1 = line_coords1.T
                #xs2, ys2 = line_coords2.T

                #linekw = dict(transform=fig.transFigure)
                #linekw = dict()

                #print('xs1 = %r' % (xs1,))
                #print('ys1 = %r' % (ys1,))

                #line1 = mpl.lines.Line2D(xs1, ys1, **linekw)
                #line2 = mpl.lines.Line2D(xs2, ys2, **linekw)  # NOQA
                #shrinkA=5, shrinkB=5, mutation_scale=20, fc="w")

                #ax2.add_artist(con)

                #fig.lines.append(line1)
                #fig.lines.append(line2)

        pass
    return fig
Example #5
0
def draw_feat_row(
    chip,
    fx,
    kp,
    sift,
    fnum,
    nRows,
    nCols=None,
    px=None,
    prevsift=None,
    origsift=None,
    aid=None,
    info="",
    type_=None,
    shape_labels=False,
    vecfield=False,
    multicolored_arms=False,
    draw_chip=False,
    draw_warped=True,
    draw_unwarped=True,
    draw_desc=True,
    rect=True,
    ori=True,
    pts=False,
    **kwargs
):
    """
    draw_feat_row

    SeeAlso:
        ibeis.viz.viz_nearest_descriptors
        ~/code/ibeis/ibeis/viz/viz_nearest_descriptors.py

    CommandLine:

        # Use this to find the fx you want to visualize
        python -m plottool.interact_keypoints --test-ishow_keypoints --show --fname zebra.png

        # Use this to visualize the featrow
        python -m plottool.viz_featrow --test-draw_feat_row --show
        python -m plottool.viz_featrow --test-draw_feat_row --show --fname zebra.png --fx=121 --feat-all --no-sift
        python -m plottool.viz_featrow --test-draw_feat_row --dpath figures --save ~/latex/crall-candidacy-2015/figures/viz_featrow.jpg

    Example:
        >>> # DISABLE_DOCTEST
        >>> from plottool.viz_featrow import *  # NOQA
        >>> import plottool as pt
        >>> # build test data
        >>> kpts, vecs, imgBGR = pt.viz_keypoints.testdata_kpts()
        >>> chip = imgBGR
        >>> print('There are %d features' % (len(vecs)))
        >>> fx = ut.get_argval('--fx', type_=int, default=0)
        >>> kp = kpts[fx]
        >>> sift = vecs[fx]
        >>> fnum = 1
        >>> nRows = 1
        >>> nCols = 2
        >>> px = 0
        >>> hack = ut.get_argflag('--feat-all')
        >>> sift = sift if not ut.get_argflag('--no-sift') else None
        >>> draw_desc = sift is not None
        >>> kw = dict(
        >>>     prevsift=None, origsift=None, aid=None, info='', type_=None,
        >>>     shape_labels=False, vecfield=False, multicolored_arms=True,
        >>>     draw_chip=hack, draw_unwarped=hack, draw_warped=True, draw_desc=draw_desc
        >>> )
        >>> # execute function
        >>> result = draw_feat_row(chip, fx, kp, sift, fnum, nRows, nCols, px,
        >>>                           rect=False, ori=False, pts=False, **kw)
        >>> # verify results
        >>> print(result)
        >>> pt.show_if_requested()
    """
    import numpy as np
    import vtool as vt

    # should not need ncols here

    if nCols is not None:
        if ut.VERBOSE:
            print("Warning nCols is no longer needed")
    # assert nCols_ == nCols
    nCols = draw_chip + draw_unwarped + draw_warped + draw_desc

    pnum_ = df2.make_pnum_nextgen(nRows, nCols, start=px)

    # pnum_ = df2.get_pnum_func(nRows, nCols, base=1)
    # countgen = itertools.count(1)

    # pnumgen_ = df2.make_pnum_nextgen(nRows, nCols, base=1)

    def _draw_patch(**kwargs):
        return df2.draw_keypoint_patch(
            chip,
            kp,
            sift,
            rect=rect,
            ori=ori,
            pts=pts,
            ori_color=custom_constants.DEEP_PINK,
            multicolored_arms=multicolored_arms,
            **kwargs
        )

    # Feature strings
    xy_str, shape_str, scale, ori_str = ph.kp_info(kp)

    if draw_chip:
        pnum = pnum_()
        df2.imshow(chip, fnum=fnum, pnum=pnum)
        kpts_kw = dict(ell_linewidth=5, ell_alpha=1.0)
        kpts_kw.update(kwargs)
        df2.draw_kpts2([kp], **kpts_kw)

    if draw_unwarped:
        # Draw the unwarped selected feature
        # ax = _draw_patch(fnum=fnum, pnum=pnum_(px + six.next(countgen)))
        # pnum = pnum_(px + six.next(countgen)
        pnum = pnum_()
        ax = _draw_patch(fnum=fnum, pnum=pnum)
        ph.set_plotdat(ax, "viztype", "unwarped")
        ph.set_plotdat(ax, "aid", aid)
        ph.set_plotdat(ax, "fx", fx)
        if shape_labels:
            unwarped_lbl = "affine feature invV =\n" + shape_str + "\n" + ori_str
            custom_figure.set_xlabel(unwarped_lbl, ax)

    if draw_warped:
        # Draw the warped selected feature
        # ax = _draw_patch(fnum=fnum, pnum=pnum_(px + six.next(countgen)), warped=True)
        pnum = pnum_()
        ax = _draw_patch(fnum=fnum, pnum=pnum, warped=True, **kwargs)
        ph.set_plotdat(ax, "viztype", "warped")
        ph.set_plotdat(ax, "aid", aid)
        ph.set_plotdat(ax, "fx", fx)
        if shape_labels:
            warped_lbl = ("warped feature\n" + "fx=%r scale=%.1f\n" + "%s") % (fx, scale, xy_str)
        else:
            warped_lbl = ""
        warped_lbl += info
        custom_figure.set_xlabel(warped_lbl, ax)

    if draw_desc:
        border_color = {
            "None": None,
            "query": None,
            "match": custom_constants.BLUE,
            "norm": custom_constants.ORANGE,
        }.get(str(type_).lower(), None)
        if border_color is not None:
            df2.draw_border(ax, color=border_color)

        # Draw the SIFT representation
        # pnum = pnum_(px + six.next(countgen))
        pnum = pnum_()
        sift_as_vecfield = ph.SIFT_OR_VECFIELD or vecfield
        if sift_as_vecfield:
            custom_figure.figure(fnum=fnum, pnum=pnum)
            df2.draw_keypoint_gradient_orientations(chip, kp, sift=sift)
        else:
            if sift.dtype.type == np.uint8:
                sigtitle = "sift histogram" if (px % 3) == 0 else ""
                ax = df2.plot_sift_signature(sift, sigtitle, fnum=fnum, pnum=pnum)
            else:
                sigtitle = "descriptor vector" if (px % 3) == 0 else ""
                ax = df2.plot_descriptor_signature(sift, sigtitle, fnum=fnum, pnum=pnum)
            ax._hs_viztype = "histogram"
        # dist_list = ['L1', 'L2', 'hist_isect', 'emd']
        # dist_list = ['L2', 'hist_isect']
        # dist_list = ['L2']
        # dist_list = ['bar_L2_sift', 'cos_sift']
        # dist_list = ['L2_sift', 'bar_cos_sift']
        dist_list = ["L2_sift"]
        dist_str_list = []
        if origsift is not None:
            distmap_orig = vt.compute_distances(sift, origsift, dist_list)
            dist_str_list.append(
                "query_dist: "
                + ", ".join(["(%s, %s)" % (key, formatdist(val)) for key, val in six.iteritems(distmap_orig)])
            )
        if prevsift is not None:
            distmap_prev = vt.compute_distances(sift, prevsift, dist_list)
            dist_str_list.append(
                "prev_dist: "
                + ", ".join(["(%s, %s)" % (key, formatdist(val)) for key, val in six.iteritems(distmap_prev)])
            )
        dist_str = "\n".join(dist_str_list)
        custom_figure.set_xlabel(dist_str)
    return px + nCols
Example #6
0
def draw_feat_row(chip,
                  fx,
                  kp,
                  sift,
                  fnum,
                  nRows,
                  nCols=None,
                  px=None,
                  prevsift=None,
                  origsift=None,
                  aid=None,
                  info='',
                  type_=None,
                  shape_labels=False,
                  vecfield=False,
                  multicolored_arms=False,
                  draw_chip=False,
                  draw_warped=True,
                  draw_unwarped=True,
                  draw_desc=True,
                  rect=True,
                  ori=True,
                  pts=False,
                  **kwargs):
    """
    draw_feat_row

    SeeAlso:
        ibeis.viz.viz_nearest_descriptors
        ~/code/ibeis/ibeis/viz/viz_nearest_descriptors.py

    CommandLine:

        # Use this to find the fx you want to visualize
        python -m plottool.interact_keypoints --test-ishow_keypoints --show --fname zebra.png

        # Use this to visualize the featrow
        python -m plottool.viz_featrow --test-draw_feat_row --show
        python -m plottool.viz_featrow --test-draw_feat_row --show --fname zebra.png --fx=121 --feat-all --no-sift
        python -m plottool.viz_featrow --test-draw_feat_row --dpath figures --save ~/latex/crall-candidacy-2015/figures/viz_featrow.jpg

    Example:
        >>> # DISABLE_DOCTEST
        >>> from plottool.viz_featrow import *  # NOQA
        >>> import plottool as pt
        >>> # build test data
        >>> kpts, vecs, imgBGR = pt.viz_keypoints.testdata_kpts()
        >>> chip = imgBGR
        >>> print('There are %d features' % (len(vecs)))
        >>> fx = ut.get_argval('--fx', type_=int, default=0)
        >>> kp = kpts[fx]
        >>> sift = vecs[fx]
        >>> fnum = 1
        >>> nRows = 1
        >>> nCols = 2
        >>> px = 0
        >>> hack = ut.get_argflag('--feat-all')
        >>> sift = sift if not ut.get_argflag('--no-sift') else None
        >>> draw_desc = sift is not None
        >>> kw = dict(
        >>>     prevsift=None, origsift=None, aid=None, info='', type_=None,
        >>>     shape_labels=False, vecfield=False, multicolored_arms=True,
        >>>     draw_chip=hack, draw_unwarped=hack, draw_warped=True, draw_desc=draw_desc
        >>> )
        >>> # execute function
        >>> result = draw_feat_row(chip, fx, kp, sift, fnum, nRows, nCols, px,
        >>>                           rect=False, ori=False, pts=False, **kw)
        >>> # verify results
        >>> print(result)
        >>> pt.show_if_requested()
    """
    import numpy as np
    import vtool as vt
    # should not need ncols here

    if nCols is not None:
        if ut.VERBOSE:
            print('Warning nCols is no longer needed')
    #assert nCols_ == nCols
    nCols = (draw_chip + draw_unwarped + draw_warped + draw_desc)

    pnum_ = df2.make_pnum_nextgen(nRows, nCols, start=px)

    #pnum_ = df2.get_pnum_func(nRows, nCols, base=1)
    #countgen = itertools.count(1)

    #pnumgen_ = df2.make_pnum_nextgen(nRows, nCols, base=1)

    def _draw_patch(**kwargs):
        return df2.draw_keypoint_patch(chip,
                                       kp,
                                       sift,
                                       rect=rect,
                                       ori=ori,
                                       pts=pts,
                                       ori_color=custom_constants.DEEP_PINK,
                                       multicolored_arms=multicolored_arms,
                                       **kwargs)

    # Feature strings
    xy_str, shape_str, scale, ori_str = ph.kp_info(kp)

    if draw_chip:
        pnum = pnum_()
        df2.imshow(chip, fnum=fnum, pnum=pnum)
        kpts_kw = dict(ell_linewidth=5, ell_alpha=1.0)
        kpts_kw.update(kwargs)
        df2.draw_kpts2([kp], **kpts_kw)

    if draw_unwarped:
        # Draw the unwarped selected feature
        #ax = _draw_patch(fnum=fnum, pnum=pnum_(px + six.next(countgen)))
        #pnum = pnum_(px + six.next(countgen)
        pnum = pnum_()
        ax = _draw_patch(fnum=fnum, pnum=pnum)
        ph.set_plotdat(ax, 'viztype', 'unwarped')
        ph.set_plotdat(ax, 'aid', aid)
        ph.set_plotdat(ax, 'fx', fx)
        if shape_labels:
            unwarped_lbl = 'affine feature invV =\n' + shape_str + '\n' + ori_str
            custom_figure.set_xlabel(unwarped_lbl, ax)

    if draw_warped:
        # Draw the warped selected feature
        #ax = _draw_patch(fnum=fnum, pnum=pnum_(px + six.next(countgen)), warped=True)
        pnum = pnum_()
        ax = _draw_patch(fnum=fnum, pnum=pnum, warped=True, **kwargs)
        ph.set_plotdat(ax, 'viztype', 'warped')
        ph.set_plotdat(ax, 'aid', aid)
        ph.set_plotdat(ax, 'fx', fx)
        if shape_labels:
            warped_lbl = ('warped feature\n' + 'fx=%r scale=%.1f\n' +
                          '%s') % (fx, scale, xy_str)
        else:
            warped_lbl = ''
        warped_lbl += info
        custom_figure.set_xlabel(warped_lbl, ax)

    if draw_desc:
        border_color = {
            'None': None,
            'query': None,
            'match': custom_constants.BLUE,
            'norm': custom_constants.ORANGE
        }.get(str(type_).lower(), None)
        if border_color is not None:
            df2.draw_border(ax, color=border_color)

        # Draw the SIFT representation
        #pnum = pnum_(px + six.next(countgen))
        pnum = pnum_()
        sift_as_vecfield = ph.SIFT_OR_VECFIELD or vecfield
        if sift_as_vecfield:
            custom_figure.figure(fnum=fnum, pnum=pnum)
            df2.draw_keypoint_gradient_orientations(chip, kp, sift=sift)
        else:
            if sift.dtype.type == np.uint8:
                sigtitle = 'sift histogram' if (px % 3) == 0 else ''
                ax = df2.plot_sift_signature(sift,
                                             sigtitle,
                                             fnum=fnum,
                                             pnum=pnum)
            else:
                sigtitle = 'descriptor vector' if (px % 3) == 0 else ''
                ax = df2.plot_descriptor_signature(sift,
                                                   sigtitle,
                                                   fnum=fnum,
                                                   pnum=pnum)
            ax._hs_viztype = 'histogram'
        #dist_list = ['L1', 'L2', 'hist_isect', 'emd']
        #dist_list = ['L2', 'hist_isect']
        #dist_list = ['L2']
        #dist_list = ['bar_L2_sift', 'cos_sift']
        #dist_list = ['L2_sift', 'bar_cos_sift']
        dist_list = ['L2_sift']
        dist_str_list = []
        if origsift is not None:
            distmap_orig = vt.compute_distances(sift, origsift, dist_list)
            dist_str_list.append('query_dist: ' + ', '.join([
                '(%s, %s)' % (key, formatdist(val))
                for key, val in six.iteritems(distmap_orig)
            ]))
        if prevsift is not None:
            distmap_prev = vt.compute_distances(sift, prevsift, dist_list)
            dist_str_list.append('prev_dist: ' + ', '.join([
                '(%s, %s)' % (key, formatdist(val))
                for key, val in six.iteritems(distmap_prev)
            ]))
        dist_str = '\n'.join(dist_str_list)
        custom_figure.set_xlabel(dist_str)
    return px + nCols