Exemple #1
0
    def show_each_dstncvs_chip(self, dodraw=True):
        """
        CommandLine:
            python -m wbia.viz.interact.interact_matches --test-show_each_dstncvs_chip --show

        Example:
            >>> # DISABLE_DOCTEST
            >>> from wbia.viz.interact.interact_matches import *  # NOQA
            >>> self = testdata_match_interact(mx=1)
            >>> self.show_each_dstncvs_chip(dodraw=False)
            >>> pt.show_if_requested()
        """
        dstncvs1, dstncvs2 = scoring.get_kpts_distinctiveness(
            self.ibs, [self.qaid, self.daid])
        logger.info('dstncvs1_stats = ' + ut.get_stats_str(dstncvs1))
        logger.info('dstncvs2_stats = ' + ut.get_stats_str(dstncvs2))
        weight_label = 'dstncvs'
        showkw = dict(weight_label=weight_label, ell=False, pts=True)
        viz_chip.show_chip(self.ibs,
                           self.qaid,
                           weights=dstncvs1,
                           fnum=pt.next_fnum(),
                           **showkw)
        viz_chip.show_chip(self.ibs,
                           self.daid,
                           weights=dstncvs2,
                           fnum=pt.next_fnum(),
                           **showkw)
        if dodraw:
            # self.draw()
            pt.draw()
def sanity_checks(offset_list, Y_list, query_annots, ibs):
    nfeat_list = np.diff(offset_list)
    for Y, nfeat in ut.ProgIter(zip(Y_list, nfeat_list), 'checking'):
        assert nfeat == sum(ut.lmap(len, Y.fxs_list))

    if False:
        # Visualize queries
        # Look at the standard query images here
        # http://www.robots.ox.ac.uk:5000/~vgg/publications/2007/Philbin07/philbin07.pdf
        from wbia.viz import viz_chip
        import wbia.plottool as pt

        pt.qt4ensure()
        fnum = 1
        pnum_ = pt.make_pnum_nextgen(len(query_annots.aids) // 5, 5)
        for aid in ut.ProgIter(query_annots.aids):
            pnum = pnum_()
            viz_chip.show_chip(
                ibs,
                aid,
                in_image=True,
                annote=False,
                notitle=True,
                draw_lbls=False,
                fnum=fnum,
                pnum=pnum,
            )
 def _show_matches_fn(aid, orank, pnum):
     """ Helper function for drawing matches to one aid """
     aug = 'rank=%r\n' % orank
     _kwshow['pnum'] = pnum
     _kwshow['title_aug'] = aug
     # draw_ell = annot_mode == 1
     # draw_lines = annot_mode >= 1
     # If we already are showing the query dont show it here
     if sidebyside:
         # Draw each match side by side the query
         if viz_name_score:
             cm.show_single_namematch(qreq_, ibs.get_annot_nids(aid),
                                      **_kwshow)
         else:
             if simplemode:
                 _kwshow['draw_border'] = False
                 _kwshow['draw_lbl'] = False
                 _kwshow['notitle'] = True
                 _kwshow['vert'] = False
                 _kwshow['modifysize'] = True
             cm.show_single_annotmatch(qreq_, aid, **_kwshow)
             # viz_matches.show_matches(ibs, cm, aid, qreq_=qreq_, **_kwshow)
     else:
         # Draw each match by themselves
         data_config2_ = None if qreq_ is None else qreq_.extern_data_config2
         # _kwshow['draw_border'] = kwargs.get('draw_border', True)
         # _kwshow['notitle'] = ut.get_argflag(('--no-title', '--notitle'))
         viz_chip.show_chip(
             ibs,
             aid,
             annote=False,
             notitle=True,
             data_config2_=data_config2_,
             **_kwshow,
         )
Exemple #4
0
 def show_each_chip(self):
     viz_chip.show_chip(self.ibs,
                        self.qaid,
                        fnum=pt.next_fnum(),
                        nokpts=True)
     viz_chip.show_chip(self.ibs,
                        self.daid,
                        fnum=pt.next_fnum(),
                        nokpts=True)
     pt.draw()
Exemple #5
0
 def show_each_fgweight_chip(self):
     viz_chip.show_chip(self.ibs,
                        self.qaid,
                        fnum=pt.next_fnum(),
                        weight_label='fg_weights')
     viz_chip.show_chip(self.ibs,
                        self.daid,
                        fnum=pt.next_fnum(),
                        weight_label='fg_weights')
     # self.draw()
     pt.draw()
 def _show_query_fn(plotx_shift, rowcols):
     """ helper for show_qres """
     plotx = plotx_shift + 1
     pnum = (rowcols[0], rowcols[1], plotx)
     # logger.info('[viz] Plotting Query: pnum=%r' % (pnum,))
     _kwshow = dict(draw_kpts=annot_mode)
     _kwshow.update(kwargs)
     _kwshow['prefix'] = 'q'
     _kwshow['pnum'] = pnum
     _kwshow['aid2_color'] = aid2_color
     _kwshow['draw_ell'] = annot_mode >= 1
     viz_chip.show_chip(ibs, cm.qaid, annote=False, qreq_=qreq_, **_kwshow)
Exemple #7
0
    def show(self, *args, **kwargs):
        if len(self) != 1:
            raise ValueError('Can only show one, got {}'.format(len(self)))
        from wbia.viz import viz_chip

        for aid in self:
            return viz_chip.show_chip(self._ibs, aid, *args, **kwargs)
    def plot_chip(self, aid, nRows, nCols, px, fulldraw=True, **kwargs):
        """ Plots an individual chip in a subaxis """
        ibs = self.ibs
        if aid in [self.aid1, self.aid2]:
            # Bold color for the matching chips
            lw = 5
            text_color = np.array((135, 206, 235, 255)) / 255.0
        else:
            lw = 2
            text_color = None

        pnum = (nRows, nCols, px)
        if not fulldraw:
            # not doing full draw so we have to clear any axes
            # that are here already manually
            ax = self.fig.add_subplot(*pnum)
            self.clear_parent_axes(ax)
            # ut.embed()
            # logger.info(subax)

        viz_chip_kw = {
            'fnum': self.fnum,
            'pnum': pnum,
            'nokpts': True,
            'show_name': True,
            'show_gname': False,
            'show_aidstr': True,
            'notitle': True,
            'show_num_gt': False,
            'text_color': text_color,
        }
        if False and ut.is_developer():
            enable_chip_title_prefix = True
            viz_chip_kw.update({
                'enable_chip_title_prefix': enable_chip_title_prefix,
                'show_name': True,
                'show_aidstr': True,
                'show_viewcode': True,
                'show_num_gt': True,
                'show_quality_text': True,
            })

        viz_chip.show_chip(ibs, aid, **viz_chip_kw)
        ax = pt.gca()
        pt.draw_border(ax, color=kwargs.get('color'), lw=lw)
        if kwargs.get('make_buttons', True):
            # divider = pt.ensure_divider(ax)
            butkw = {
                # 'divider': divider,
                'ax': ax,
                'size': '13%'
                # 'size': '15%'
            }
        # Chip matching/naming options
        nid = ibs.get_annot_name_rowids(aid)
        annotation_unknown = ibs.is_nid_unknown([nid])[0]
        if not annotation_unknown:
            # remove name
            callback = functools.partial(self.unname_annotation, aid)
            self.append_button(
                'remove name (' + ibs.get_name_texts(nid) + ')',
                callback=callback,
                **butkw,
            )
        else:
            # new name
            callback = functools.partial(self.mark_annotation_as_new_name, aid)
            self.append_button('mark as new name', callback=callback, **butkw)
        if (nid != self.nid2 and not ibs.is_nid_unknown([self.nid2])[0]
                and not self.is_split_case):
            # match to nid2
            callback = functools.partial(self.rename_annotation, aid,
                                         self.nid2)
            text = 'match to name2: ' + ibs.get_name_texts(self.nid2)
            self.append_button(text, callback=callback, **butkw)
        if nid != self.nid1 and not ibs.is_nid_unknown([self.nid1])[0]:
            # match to nid1
            callback = functools.partial(self.rename_annotation, aid,
                                         self.nid1)
            text = 'match to name1: ' + ibs.get_name_texts(self.nid1)
            self.append_button(text, callback=callback, **butkw)

        other_nid_list = self.get_other_nids()
        for other_nid in other_nid_list:
            if other_nid == nid:
                continue
            # rename nid2
            callback = functools.partial(self.rename_annotation, aid,
                                         other_nid)
            text = 'match to: ' + ibs.get_name_texts(other_nid)
            self.append_button(text, callback=callback, **butkw)
        return ax
Exemple #9
0
def show_annot(ibs, aid, *args, **kwargs):
    """ viz helper see wbia.viz.viz_chip.show_chip """
    from wbia.viz import viz_chip

    return viz_chip.show_chip(ibs, aid, *args, **kwargs)
Exemple #10
0
def show_multiple_chips(ibs,
                        aid_list,
                        in_image=True,
                        fnum=0,
                        sel_aids=[],
                        subtitle='',
                        annote=False,
                        **kwargs):
    """
    CommandLine:
        python -m wbia.viz.viz_name --test-show_multiple_chips --show --no-inimage
        python -m wbia.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 wbia.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 wbia.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 wbia.viz.viz_name --test-show_multiple_chips --show --db PZ_Master0 --aids=1288 --no-inimage --notitle --adjust=.05
        python -m wbia.viz.viz_name --test-show_multiple_chips --show --db PZ_Master0 --aids=4020,4839 --no-inimage --notitle --adjust=.05

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

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

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

        python -m wbia.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 wbia.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 wbia.viz.viz_name import *  # NOQA
        >>> import wbia
        >>> ibs, aid_list, in_image = testdata_multichips()
        >>> if True:
        >>>     import matplotlib as mpl
        >>>     from wbia.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)

    logger.info('[viz_name] * annot_vuuid=%r' %
                ((ibs.get_annot_visual_uuids(aid_list), )))
    logger.info('[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)
    # logger.info('[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):
        logger.info('px = %r' % (px, ))
        _fig, _ax1 = viz_chip.show_chip(ibs,
                                        aid=aid,
                                        pnum=pnum_(px),
                                        **show_chip_kw)
        logger.info('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
            # logger.info(ax_list1)
            # logger.info(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]
                logger.info('--')
                logger.info('ax1 = %r' % (ax1, ))
                logger.info('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]

                logger.info('bbox1 = %r' % (bbox1, ))
                logger.info('bbox2 = %r' % (bbox2, ))

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

                logger.info('vert_list1 = %r' % (vert_list1, ))
                logger.info('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()
                    logger.info('  ***')
                    logger.info('  * vert1 = %r' % (vert1, ))
                    logger.info('  * 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))
                # logger.info('bottom_left2 = %r' % (bottom_left2,))
                # coord_bl1 = (5, 5)
                # coord_bl2 = invTransFigure_fn2(transAxes2_fn(bottom_left2))
                # logger.info('coord_bl2 = %r' % (coord_bl2,))

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

                # line_coords1 = np.vstack([coord_bl1, coord_bl2])
                # line_coords2 = np.vstack([coord_br1, coord_br2])
                # logger.info('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()

                # logger.info('xs1 = %r' % (xs1,))
                # logger.info('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
Exemple #11
0
    def plot_chip(self, aid, nRows, nCols, px, **kwargs):
        """ Plots an individual chip in a subaxis """
        ibs = self.ibs
        enable_chip_title_prefix = ut.is_developer()
        # enable_chip_title_prefix = False
        if aid in self.comp_aids:
            score = self.cm.get_annot_scores([aid])[0]
            rawscore = self.cm.get_annot_scores([aid])[0]
            title_suf = kwargs.get('title_suffix', '')
            if score != rawscore:
                if score is None:
                    title_suf += '\n score=____'
                else:
                    title_suf += '\n score=%0.2f' % score
            title_suf += '\n rawscore=%0.2f' % rawscore
        else:
            title_suf = kwargs.get('title_suffix', '')
            if enable_chip_title_prefix:
                title_suf = '\n' + title_suf

        # nid = ibs.get_annot_name_rowids(aid)
        viz_chip_kw = {
            'fnum': self.fnum,
            'pnum': (nRows, nCols, px),
            'nokpts': True,
            'show_gname': False,
            'show_exemplar': False,
            'show_num_gt': False,
            'show_gname': False,
            'title_suffix': title_suf,
            # 'text_color': kwargs.get('color'),
            ###
            # 'show_name': False,
            # 'show_aidstr': False,
            'enable_chip_title_prefix': enable_chip_title_prefix,
            'show_name': True,
            'show_aidstr': True,
            'show_viewcode': True,
            'show_quality_text': True,
        }

        viz_chip.show_chip(ibs, aid, **viz_chip_kw)
        ax = pt.gca()
        if kwargs.get('make_buttons', True):
            divider = pt.ensure_divider(ax)
            butkw = {'divider': divider, 'size': '13%'}

        self.aid2_ax = {}
        self.aid2_border = {}

        if aid in self.comp_aids:
            callback = partial(self.select, aid)
            self.append_button('Select This Animal', callback=callback, **butkw)
            # Hack to toggle colors
            if aid in self.aid_checkbox_states:
                # If we are selecting it, then make it green, otherwise change it back to grey
                if self.aid_checkbox_states[aid]:
                    border = pt.draw_border(ax, color=(0, 1, 0), lw=4)
                else:
                    border = pt.draw_border(ax, color=(0.7, 0.7, 0.7), lw=4)
                self.aid2_border[aid] = border
            else:
                self.aid_checkbox_states[aid] = False
            self.append_button('Examine', callback=partial(self.examine, aid), **butkw)