Esempio n. 1
0
def make_colorcodes(model):
    """
        python -m ibeis.algo.hots.bayes --exec-make_name_model --show
        python -m ibeis.algo.hots.bayes --exec-cluster_query --show
        python -m ibeis --tf demo_bayesnet --ev :nA=4,nS=2,Na=n0,rand_scores=True --show --verbose
        python -m ibeis --tf demo_bayesnet --ev :nA=4,nS=3,Na=n0,rand_scores=True --show --verbose
    """
    import plottool as pt
    ttype_colors = {}
    ttype_scalars = {}

    # Hacked in custom colors

    if 'name' in model.ttype2_template:
        basis = model.ttype2_template['name'].basis
        card = len(basis)
        colors = pt.distinct_colors(max(card, 10))[:card]
        ttype_colors['name'] = colors
        ttype_scalars['name'] = np.linspace(0, 1, len(basis))

    if 'score' in model.ttype2_template:
        cmap_, mn, mx = 'plasma', 0.15, 1.0
        _cmap = pt.plt.get_cmap(cmap_)
        def cmap(x):
            return _cmap((x * mx) + mn)
        basis = model.ttype2_template['score'].basis
        scalars = np.linspace(0, 1, len(basis))
        # scalars = np.linspace(0, 1, 100)
        colors = pt.scores_to_color(scalars, cmap_=cmap_, reverse_cmap=False,
                                    cmap_range=(mn, mx))
        colors = [pt.lighten_rgb(c, .4) for c in colors]
        ttype_scalars['score'] = scalars
        ttype_colors['score'] = colors

    return ttype_colors, ttype_scalars
Esempio n. 2
0
 def get_colored_weights(infr, weights):
     import plottool as pt
     #pt.rrrr()
     # cmap_ = 'viridis'
     # cmap_ = 'plasma'
     # cmap_ = pt.plt.cm.RdYlBu
     cmap_ = infr._get_cmap()
     # cmap_ = pt.plt.cm.RdYlBu
     #cmap_ = pt.plt.get_cmap(cmap_)
     thresh = .5
     weights[np.isnan(weights)] = thresh
     #colors = pt.scores_to_color(weights, cmap_=cmap_, logscale=True)
     colors = pt.scores_to_color(weights,
                                 cmap_=cmap_,
                                 score_range=(0, 1),
                                 logscale=False,
                                 cmap_range=None)
     return colors
Esempio n. 3
0
def make_colorcodes(model):
    """
        python -m ibeis.algo.hots.bayes --exec-make_name_model --show
        python -m ibeis.algo.hots.bayes --exec-cluster_query --show
        python -m ibeis --tf demo_bayesnet --ev :nA=4,nS=2,Na=n0,rand_scores=True --show --verbose
        python -m ibeis --tf demo_bayesnet --ev :nA=4,nS=3,Na=n0,rand_scores=True --show --verbose
    """
    import plottool as pt
    ttype_colors = {}
    ttype_scalars = {}

    # Hacked in custom colors

    if 'name' in model.ttype2_template:
        basis = model.ttype2_template['name'].basis
        card = len(basis)
        colors = pt.distinct_colors(max(card, 10))[:card]
        ttype_colors['name'] = colors
        ttype_scalars['name'] = np.linspace(0, 1, len(basis))

    if 'score' in model.ttype2_template:
        cmap_, mn, mx = 'plasma', 0.15, 1.0
        _cmap = pt.plt.get_cmap(cmap_)

        def cmap(x):
            return _cmap((x * mx) + mn)

        basis = model.ttype2_template['score'].basis
        scalars = np.linspace(0, 1, len(basis))
        # scalars = np.linspace(0, 1, 100)
        colors = pt.scores_to_color(scalars,
                                    cmap_=cmap_,
                                    reverse_cmap=False,
                                    cmap_range=(mn, mx))
        colors = [pt.lighten_rgb(c, .4) for c in colors]
        ttype_scalars['score'] = scalars
        ttype_colors['score'] = colors

    return ttype_colors, ttype_scalars
Esempio n. 4
0
def show_multichip_match(rchip1,
                         rchip2_list,
                         kpts1,
                         kpts2_list,
                         fm_list,
                         fs_list,
                         featflag_list,
                         fnum=None,
                         pnum=None,
                         **kwargs):
    """
    move to df2
    rchip = rchip1
    H = H1 = None
    target_wh = None

    """
    import vtool.image as gtool
    import plottool as pt
    import numpy as np
    import vtool as vt
    kwargs = kwargs.copy()

    colorbar_ = kwargs.pop('colorbar_', True)
    stack_larger = kwargs.pop('stack_larger', False)
    # mode for features disabled by name scoring
    NONVOTE_MODE = kwargs.get('nonvote_mode', 'filter')

    def preprocess_chips(rchip, H, target_wh):
        rchip_ = rchip if H is None else gtool.warpHomog(rchip, H, target_wh)
        return rchip_

    if fnum is None:
        fnum = pt.next_fnum()

    target_wh1 = None
    H1 = None
    rchip1_ = preprocess_chips(rchip1, H1, target_wh1)
    # Hack to visually identify the query
    rchip1_ = vt.draw_border(rchip1_,
                             out=rchip1_,
                             thickness=15,
                             color=(pt.UNKNOWN_PURP[0:3] * 255).astype(
                                 np.uint8).tolist())
    wh1 = gtool.get_size(rchip1_)
    rchip2_list_ = [
        preprocess_chips(rchip2, None, wh1) for rchip2 in rchip2_list
    ]
    wh2_list = [gtool.get_size(rchip2) for rchip2 in rchip2_list_]

    num = 0 if len(rchip2_list) < 3 else 1
    #vert = True if len(rchip2_list) > 1 else False
    vert = True if len(rchip2_list) > 1 else None
    #num = 0

    if False and kwargs.get('fastmode', False):
        # This doesn't actually help the speed very much
        stackkw = dict(
            # Hack draw results faster Q
            #initial_sf=.4,
            #initial_sf=.9,
            use_larger=stack_larger,
            #use_larger=True,
        )
    else:
        stackkw = dict()
    #use_larger = True
    #vert = kwargs.get('fastmode', False)

    match_img, offset_list, sf_list = vt.stack_image_list_special(rchip1_,
                                                                  rchip2_list_,
                                                                  num=num,
                                                                  vert=vert,
                                                                  **stackkw)
    wh_list = np.array(ut.flatten([[wh1], wh2_list])) * sf_list

    offset1 = offset_list[0]
    wh1 = wh_list[0]
    sf1 = sf_list[0]

    fig, ax = pt.imshow(match_img, fnum=fnum, pnum=pnum)

    if kwargs.get('show_matches', True):
        ut.flatten(fs_list)
        #ut.embed()
        flat_fs, cumlen_list = ut.invertible_flatten2(fs_list)
        flat_colors = pt.scores_to_color(np.array(flat_fs), 'hot')
        colors_list = ut.unflatten2(flat_colors, cumlen_list)
        for _tup in zip(offset_list[1:], wh_list[1:], sf_list[1:], kpts2_list,
                        fm_list, fs_list, featflag_list, colors_list):
            offset2, wh2, sf2, kpts2, fm2_, fs2_, featflags, colors = _tup
            xywh1 = (offset1[0], offset1[1], wh1[0], wh1[1])
            xywh2 = (offset2[0], offset2[1], wh2[0], wh2[1])
            #colors = pt.scores_to_color(fs2)
            if kpts1 is not None and kpts2 is not None:
                if NONVOTE_MODE == 'filter':
                    fm2 = fm2_.compress(featflags, axis=0)
                    fs2 = fs2_.compress(featflags, axis=0)
                elif NONVOTE_MODE == 'only':
                    fm2 = fm2_.compress(np.logical_not(featflags), axis=0)
                    fs2 = fs2_.compress(np.logical_not(featflags), axis=0)
                else:
                    # TODO: optional coloring of nonvotes instead
                    fm2 = fm2_
                    fs2 = fs2_
                pt.plot_fmatch(xywh1,
                               xywh2,
                               kpts1,
                               kpts2,
                               fm2,
                               fs2,
                               fm_norm=None,
                               H1=None,
                               H2=None,
                               scale_factor1=sf1,
                               scale_factor2=sf2,
                               colorbar_=False,
                               colors=colors,
                               **kwargs)
        if colorbar_:
            pt.colorbar(flat_fs, flat_colors)
    bbox_list = [(x, y, w, h) for (x, y), (w, h) in zip(offset_list, wh_list)]
    return offset_list, sf_list, bbox_list
Esempio n. 5
0
def show_model(model, evidence={}, soft_evidence={}, **kwargs):
    """
    References:
        http://stackoverflow.com/questions/22207802/pygraphviz-networkx-set-node-level-or-layer

    Ignore:
        pkg-config --libs-only-L libcgraph
        sudo apt-get  install libgraphviz-dev -y
        sudo apt-get  install libgraphviz4 -y

        # sudo apt-get install pkg-config
        sudo apt-get install libgraphviz-dev
        # pip install git+git://github.com/pygraphviz/pygraphviz.git
        pip install pygraphviz
        python -c "import pygraphviz; print(pygraphviz.__file__)"

        sudo pip3 install pygraphviz --install-option="--include-path=/usr/include/graphviz" --install-option="--library-path=/usr/lib/graphviz/"
        python3 -c "import pygraphviz; print(pygraphviz.__file__)"

    CommandLine:
        python -m ibeis.algo.hots.bayes --exec-show_model --show

    Example:
        >>> # DISABLE_DOCTEST
        >>> from ibeis.algo.hots.bayes import *  # NOQA
        >>> model = '?'
        >>> evidence = {}
        >>> soft_evidence = {}
        >>> result = show_model(model, evidence, soft_evidence)
        >>> print(result)
        >>> ut.quit_if_noshow()
        >>> import plottool as pt
        >>> ut.show_if_requested()
    """
    if ut.get_argval('--hackmarkov') or ut.get_argval('--hackjunc'):
        draw_tree_model(model, **kwargs)
        return

    import plottool as pt
    import networkx as netx
    fnum = pt.ensure_fnum(None)
    netx_graph = (model)
    #netx_graph.graph.setdefault('graph', {})['size'] = '"10,5"'
    #netx_graph.graph.setdefault('graph', {})['rankdir'] = 'LR'

    pos_dict = get_hacked_pos(netx_graph)
    #pos_dict = netx.pygraphviz_layout(netx_graph)
    #pos = netx.pydot_layout(netx_graph, prog='dot')
    #pos_dict = netx.graphviz_layout(netx_graph)

    textprops = {
        'family': 'monospace',
        'horizontalalignment': 'left',
        #'horizontalalignment': 'center',
        #'size': 12,
        'size': 8,
    }

    netx_nodes = model.nodes(data=True)
    node_key_list = ut.get_list_column(netx_nodes, 0)
    pos_list = ut.dict_take(pos_dict, node_key_list)

    var2_post = {f.variables[0]: f for f in kwargs.get('factor_list', [])}

    prior_text = None
    post_text = None
    evidence_tas = []
    post_tas = []
    prior_tas = []
    node_color = []

    has_infered = evidence or var2_post
    if has_infered:
        ignore_prior_with_ttype = ['score', 'match']
        show_prior = False
    else:
        ignore_prior_with_ttype = []
        #show_prior = True
        show_prior = False

    dpy = 5
    dbx, dby = (20, 20)
    takw1 = {'bbox_align': (.5, 0), 'pos_offset': [0, dpy], 'bbox_offset': [dbx, dby]}
    takw2 = {'bbox_align': (.5, 1), 'pos_offset': [0, -dpy], 'bbox_offset': [-dbx, -dby]}

    name_colors = pt.distinct_colors(max(model.num_names, 10))
    name_colors = name_colors[:model.num_names]

    #cmap_ = 'hot' #mx = 0.65 #mn = 0.15
    cmap_, mn, mx = 'plasma', 0.15, 1.0
    _cmap = pt.plt.get_cmap(cmap_)
    def cmap(x):
        return _cmap((x * mx) + mn)

    for node, pos in zip(netx_nodes, pos_list):
        variable = node[0]
        cpd = model.var2_cpd[variable]
        prior_marg = (cpd if cpd.evidence is None else
                      cpd.marginalize(cpd.evidence, inplace=False))

        show_evidence = variable in evidence
        show_prior = cpd.ttype not in ignore_prior_with_ttype
        show_post = variable in var2_post
        show_prior |= cpd.ttype not in ignore_prior_with_ttype

        post_marg = None

        if show_post:
            post_marg = var2_post[variable]

        def get_name_color(phi):
            order = phi.values.argsort()[::-1]
            if len(order) < 2:
                dist_next = phi.values[order[0]]
            else:
                dist_next = phi.values[order[0]] - phi.values[order[1]]
            dist_total = (phi.values[order[0]])
            confidence = (dist_total * dist_next) ** (2.5 / 4)
            #print('confidence = %r' % (confidence,))
            color = name_colors[order[0]]
            color = pt.color_funcs.desaturate_rgb(color, 1 - confidence)
            color = np.array(color)
            return color

        if variable in evidence:
            if cpd.ttype == 'score':
                cmap_index = evidence[variable] / (cpd.variable_card - 1)
                color = cmap(cmap_index)
                color = pt.lighten_rgb(color, .4)
                color = np.array(color)
                node_color.append(color)
            elif cpd.ttype == 'name':
                color = name_colors[evidence[variable]]
                color = np.array(color)
                node_color.append(color)
            else:
                color = pt.FALSE_RED
                node_color.append(color)
        #elif variable in soft_evidence:
        #    color = pt.LIGHT_PINK
        #    show_prior = True
        #    color = get_name_color(prior_marg)
        #    node_color.append(color)
        else:
            if cpd.ttype == 'name' and post_marg is not None:
                color = get_name_color(post_marg)
                node_color.append(color)
            elif cpd.ttype == 'match' and post_marg is not None:
                color = cmap(post_marg.values[1])
                color = pt.lighten_rgb(color, .4)
                color = np.array(color)
                node_color.append(color)
            else:
                #color = pt.WHITE
                color = pt.NEUTRAL
                node_color.append(color)

        if show_prior:
            if variable in soft_evidence:
                prior_color = pt.LIGHT_PINK
            else:
                prior_color = None
            prior_text = pgm_ext.make_factor_text(prior_marg, 'prior')
            prior_tas.append(dict(text=prior_text, pos=pos, color=prior_color, **takw2))
        if show_evidence:
            _takw1 = takw1
            if cpd.ttype == 'score':
                _takw1 = takw2
            evidence_text = cpd.variable_statenames[evidence[variable]]
            if isinstance(evidence_text, int):
                evidence_text = '%d/%d' % (evidence_text + 1, cpd.variable_card)
            evidence_tas.append(dict(text=evidence_text, pos=pos, color=color, **_takw1))
        if show_post:
            _takw1 = takw1
            if cpd.ttype == 'match':
                _takw1 = takw2
            post_text = pgm_ext.make_factor_text(post_marg, 'post')
            post_tas.append(dict(text=post_text, pos=pos, color=None, **_takw1))

    def trnps_(dict_list):
        """ tranpose dict list """
        list_dict = ut.ddict(list)
        for dict_ in dict_list:
            for key, val in dict_.items():
                list_dict[key + '_list'].append(val)
        return list_dict

    takw1_ = trnps_(post_tas + evidence_tas)
    takw2_ = trnps_(prior_tas)

    # Draw graph
    if has_infered:
        pnum1 = (3, 1, (slice(0, 2), 0))
    else:
        pnum1 = None

    fig = pt.figure(fnum=fnum, pnum=pnum1, doclf=True)  # NOQA
    ax = pt.gca()
    #print('node_color = %s' % (ut.repr3(node_color),))
    drawkw = dict(pos=pos_dict, ax=ax, with_labels=True, node_size=1500,
                  node_color=node_color)
    netx.draw(netx_graph, **drawkw)

    hacks = []
    if len(post_tas + evidence_tas):
        hacks.append(pt.draw_text_annotations(textprops=textprops, **takw1_))
    if prior_tas:
        hacks.append(pt.draw_text_annotations(textprops=textprops, **takw2_))

    xmin, ymin = np.array(pos_list).min(axis=0)
    xmax, ymax = np.array(pos_list).max(axis=0)
    num_annots = len(model.ttype2_cpds['name'])
    if num_annots > 4:
        ax.set_xlim((xmin - 40, xmax + 40))
        ax.set_ylim((ymin - 50, ymax + 50))
        fig.set_size_inches(30, 7)
    else:
        ax.set_xlim((xmin - 42, xmax + 42))
        ax.set_ylim((ymin - 50, ymax + 50))
        fig.set_size_inches(23, 7)
    fig = pt.gcf()

    title = 'num_names=%r, num_annots=%r' % (model.num_names, num_annots,)
    map_assign = kwargs.get('map_assign', None)

    top_assignments = kwargs.get('top_assignments', None)
    if top_assignments is not None:
        map_assign, map_prob = top_assignments[0]
        if map_assign is not None:
            def word_insert(text):
                return '' if len(text) == 0 else text + ' '
            title += '\n%sMAP: ' % (word_insert(kwargs.get('method', '')))
            title += map_assign + ' @' + '%.2f%%' % (100 * map_prob,)
    if kwargs.get('show_title', True):
        pt.set_figtitle(title, size=14)

    for hack in hacks:
        hack()

    # Hack in colorbars
    if has_infered:
        pt.colorbar(np.linspace(0, 1, len(name_colors)), name_colors, lbl='name',
                    ticklabels=model.ttype2_template['name'].basis, ticklocation='left')

        basis = model.ttype2_template['score'].basis
        scalars = np.linspace(0, 1, len(basis))
        scalars = np.linspace(0, 1, 100)
        colors = pt.scores_to_color(scalars, cmap_=cmap_, reverse_cmap=False,
                                    cmap_range=(mn, mx))
        colors = [pt.lighten_rgb(c, .4) for c in colors]

        if ut.list_type(basis) is int:
            pt.colorbar(scalars, colors, lbl='score', ticklabels=np.array(basis) + 1)
        else:
            pt.colorbar(scalars, colors, lbl='score', ticklabels=basis)
            #print('basis = %r' % (basis,))

    # Draw probability hist
    if has_infered and top_assignments is not None:
        bin_labels = ut.get_list_column(top_assignments, 0)
        bin_vals =  ut.get_list_column(top_assignments, 1)

        # bin_labels = ['\n'.join(ut.textwrap.wrap(_lbl, width=30)) for _lbl in bin_labels]

        pt.draw_histogram(bin_labels, bin_vals, fnum=fnum, pnum=(3, 8, (2, slice(4, None))),
                          transpose=True,
                          use_darkbackground=False,
                          #xtick_rotation=-10,
                          ylabel='Prob', xlabel='assignment')
        pt.set_title('Assignment probabilities')
Esempio n. 6
0
def show_chip(ibs,
              aid,
              in_image=False,
              annote=True,
              title_suffix='',
              weight_label=None,
              weights=None,
              config2_=None,
              **kwargs):
    r""" Driver function to show chips

    Args:
        ibs (ibeis.IBEISController):
        aid (int): annotation rowid
        in_image (bool): displays annotation with the context of its source image
        annote (bool): enables overlay annoations
        title_suffix (str):
        weight_label (None): (default = None)
        weights (None): (default = None)
        config2_ (dict): (default = None)

    Kwargs:
        enable_chip_title_prefix, nokpts, kpts_subset, kpts, text_color,
        notitle, draw_lbls, show_aidstr, show_gname, show_name, show_nid,
        show_exemplar, show_num_gt, show_quality_text, show_yawtext, fnum,
        title, figtitle, pnum, interpolation, cmap, heatmap, data_colorbar,
        darken, update, xlabel, redraw_image, ax, alpha, docla, doclf,
        projection, use_gridspec, pts, ell
        color (3/4-tuple, ndarray, or str): colors for keypoints

    CommandLine:
        python -m ibeis.viz.viz_chip --test-show_chip --show --ecc
        python -c "import utool as ut; ut.print_auto_docstr('ibeis.viz.viz_chip', 'show_chip')"
        python -m ibeis.viz.viz_chip --test-show_chip --show --db NNP_Master3 --aids 14047 --no-annote
        python -m ibeis.viz.viz_chip --test-show_chip --show --db NNP_Master3 --aids 14047 --no-annote

        python -m ibeis.viz.viz_chip --test-show_chip --show --db PZ_MTEST --aid 1 --bgmethod=cnn
        python -m ibeis.viz.viz_chip --test-show_chip --show --db PZ_MTEST --aid 1 --bgmethod=cnn --scale_max=30

    Example:
        >>> # VIZ_TEST
        >>> from ibeis.viz.viz_chip import *  # NOQA
        >>> import numpy as np
        >>> import vtool as vt
        >>> in_image = False
        >>> ibs, aid_list, kwargs, config2_ = testdata_showchip()
        >>> aid = aid_list[0]
        >>> if ut.get_argflag('--ecc'):
        >>>     kpts = ibs.get_annot_kpts(aid, config2_=config2_)
        >>>     weights = ibs.get_annot_fgweights([aid], ensure=True, config2_=config2_)[0]
        >>>     kpts = ut.random_sample(kpts[weights > .9], 200, seed=0)
        >>>     ecc = vt.get_kpts_eccentricity(kpts)
        >>>     scale = 1 / vt.get_scales(kpts)
        >>>     s = ecc if config2_.affine_invariance else scale
        >>>     colors = pt.scores_to_color(s, cmap_='jet')
        >>>     kwargs['color'] = colors
        >>>     kwargs['kpts'] = kpts
        >>> show_chip(ibs, aid, in_image=in_image, config2_=config2_, **kwargs)
        >>> pt.show_if_requested()
    """
    if ut.VERBOSE:
        print('[viz] show_chip(aid=%r)' % (aid, ))
    #ibs.assert_valid_aids((aid,))
    # Get chip
    #print('in_image = %r' % (in_image,))
    chip = vh.get_chips(ibs, aid, in_image=in_image, config2_=config2_)
    # Create chip title
    chip_text = vh.get_annot_texts(ibs, [aid], **kwargs)[0]
    if kwargs.get('enable_chip_title_prefix', True):
        chip_title_text = chip_text + title_suffix
    else:
        chip_title_text = title_suffix
    chip_title_text = chip_title_text.strip('\n')
    # Draw chip
    fig, ax = pt.imshow(chip, **kwargs)
    # Populate axis user data
    vh.set_ibsdat(ax, 'viztype', 'chip')
    vh.set_ibsdat(ax, 'aid', aid)
    if annote and not kwargs.get('nokpts', False):
        # Get and draw keypoints
        if 'color' not in kwargs:
            if weight_label == 'fg_weights':
                if weights is None and ibs.has_species_detector(
                        ibs.get_annot_species_texts(aid)):
                    weight_label = 'fg_weights'
                    weights = ibs.get_annot_fgweights([aid],
                                                      ensure=True,
                                                      config2_=config2_)[0]
            if weights is not None:
                cmap_ = 'hot'
                #if weight_label == 'dstncvs':
                #    cmap_ = 'rainbow'
                color = pt.scores_to_color(weights,
                                           cmap_=cmap_,
                                           reverse_cmap=False)
                kwargs['color'] = color
                kwargs['ell_color'] = color
                kwargs['pts_color'] = color

        kpts_ = vh.get_kpts(ibs,
                            aid,
                            in_image,
                            config2_=config2_,
                            kpts_subset=kwargs.get('kpts_subset', None),
                            kpts=kwargs.get('kpts', None))
        try:
            del kwargs['kpts']
        except KeyError:
            pass
        pt.viz_keypoints._annotate_kpts(kpts_, **kwargs)
        if not ut.get_argflag('--noaidlabel'):
            pt.upperleft_text(chip_text, color=kwargs.get('text_color', None))
    use_title = not kwargs.get('notitle', False)
    if use_title:
        pt.set_title(chip_title_text)
    if in_image:
        gid = ibs.get_annot_gids(aid)
        aid_list = ibs.get_image_aids(gid)
        annotekw = viz_image.get_annot_annotations(ibs,
                                                   aid_list,
                                                   sel_aids=[aid],
                                                   draw_lbls=kwargs.get(
                                                       'draw_lbls', True))
        # Put annotation centers in the axis
        ph.set_plotdat(ax, 'annotation_bbox_list', annotekw['bbox_list'])
        ph.set_plotdat(ax, 'aid_list', aid_list)
        pt.viz_image2.draw_image_overlay(ax, **annotekw)

        zoom_ = ut.get_argval('--zoom', type_=float, default=None)
        if zoom_ is not None:
            import vtool as vt
            # Zoom into the chip for some image context
            rotated_verts = ibs.get_annot_rotated_verts(aid)
            bbox = ibs.get_annot_bboxes(aid)
            #print(bbox)
            #print(rotated_verts)
            rotated_bbox = vt.bbox_from_verts(rotated_verts)
            imgw, imgh = ibs.get_image_sizes(gid)

            pad_factor = zoom_
            pad_length = min(bbox[2], bbox[3]) * pad_factor
            minx = max(rotated_bbox[0] - pad_length, 0)
            miny = max(rotated_bbox[1] - pad_length, 0)
            maxx = min((rotated_bbox[0] + rotated_bbox[2]) + pad_length, imgw)
            maxy = min((rotated_bbox[1] + rotated_bbox[3]) + pad_length, imgh)

            #maxy = imgh - maxy
            #miny = imgh - miny

            ax = pt.gca()
            ax.set_xlim(minx, maxx)
            ax.set_ylim(miny, maxy)
            ax.invert_yaxis()
    else:
        ph.set_plotdat(ax, 'chipshape', chip.shape)

    #if 'featweights' in vars() and 'color' in kwargs:
    if weights is not None and weight_label is not None:
        ## HACK HACK HACK
        if len(weights) > 0:
            cb = pt.colorbar(weights, kwargs['color'])
            cb.set_label(weight_label)
    return fig, ax
Esempio n. 7
0
    def initialize_graph_and_model(infr):
        """ Unused in internal split stuff

        pt.qt4ensure()
        layout_info = pt.show_nx(graph, as_directed=False, fnum=1,
                                 layoutkw=dict(prog='neato'), use_image=True,
                                 verbose=0)
        ax = pt.gca()
        pt.zoom_factory()
        pt.interactions.PanEvents()
        """
        #import networkx as nx
        #import itertools
        cm_list = infr.cm_list
        hack = True
        hack = False
        if hack:
            cm_list = cm_list[:10]
        qaid_list = [cm.qaid for cm in cm_list]
        daids_list = [cm.daid_list for cm in cm_list]
        unique_aids = sorted(ut.list_union(*daids_list + [qaid_list]))
        if hack:
            unique_aids = sorted(ut.isect(unique_aids, qaid_list))
        aid2_aidx = ut.make_index_lookup(unique_aids)

        # Construct K-broken graph
        edges = []
        edge_weights = []
        #top = (infr.qreq_.qparams.K + 1) * 2
        #top = (infr.qreq_.qparams.K) * 2
        top = (infr.qreq_.qparams.K + 2)
        for count, cm in enumerate(cm_list):
            qidx = aid2_aidx[cm.qaid]
            score_list = cm.annot_score_list
            sortx = ut.argsort(score_list)[::-1]
            score_list = ut.take(score_list, sortx)[:top]
            daid_list = ut.take(cm.daid_list, sortx)[:top]
            for score, daid in zip(score_list, daid_list):
                if daid not in qaid_list:
                    continue
                didx = aid2_aidx[daid]
                edge_weights.append(score)
                edges.append((qidx, didx))

        # make symmetric
        directed_edges = dict(zip(edges, edge_weights))
        # Find edges that point in both directions
        undirected_edges = {}
        for (u, v), w in directed_edges.items():
            if (v, u) in undirected_edges:
                undirected_edges[(v, u)] += w
                undirected_edges[(v, u)] /= 2
            else:
                undirected_edges[(u, v)] = w

        edges = list(undirected_edges.keys())
        edge_weights = list(undirected_edges.values())
        nodes = list(range(len(unique_aids)))

        nid_labeling = infr.qreq_.ibs.get_annot_nids(unique_aids)
        labeling = ut.rebase_labels(nid_labeling)

        import networkx as nx
        from ibeis.viz import viz_graph
        set_node_attrs = nx.set_node_attributes
        set_edge_attrs = nx.set_edge_attributes

        # Create match-based graph structure
        graph = nx.DiGraph()
        graph.add_nodes_from(nodes)
        graph.add_edges_from(edges)

        # Important properties
        nid_list = infr.qreq_.ibs.get_annot_nids(unique_aids)
        labeling = ut.rebase_labels(nid_list)

        set_node_attrs(graph, 'name_label', dict(zip(nodes, labeling)))
        set_edge_attrs(graph, 'weight', dict(zip(edges, edge_weights)))

        # Visualization properties
        import plottool as pt
        ax2_aid = ut.invert_dict(aid2_aidx)
        set_node_attrs(graph, 'aid', ax2_aid)
        viz_graph.ensure_node_images(infr.qreq_.ibs, graph)
        set_node_attrs(graph, 'framewidth', dict(zip(nodes,
                                                     [3.0] * len(nodes))))
        set_node_attrs(graph, 'framecolor',
                       dict(zip(nodes, [pt.DARK_BLUE] * len(nodes))))
        ut.color_nodes(graph, labelattr='name_label')

        edge_colors = pt.scores_to_color(np.array(edge_weights),
                                         cmap_='viridis')
        #import utool
        #utool.embed()
        #edge_colors = [pt.color_funcs.ensure_base255(color) for color in edge_colors]
        #print('edge_colors = %r' % (edge_colors,))
        set_edge_attrs(graph, 'color', dict(zip(edges, edge_colors)))

        # Build inference model
        from ibeis.algo.hots import graph_iden
        #graph_iden.rrr()
        model = graph_iden.InfrModel(graph)
        #model = graph_iden.InfrModel(len(nodes), edges, edge_weights, labeling=labeling)
        infr.model = model
Esempio n. 8
0
def show_model(model, evidence={}, soft_evidence={}, **kwargs):
    """
    References:
        http://stackoverflow.com/questions/22207802/pygraphviz-networkx-set-node-level-or-layer

    Ignore:
        pkg-config --libs-only-L libcgraph
        sudo apt-get  install libgraphviz-dev -y
        sudo apt-get  install libgraphviz4 -y

        # sudo apt-get install pkg-config
        sudo apt-get install libgraphviz-dev
        # pip install git+git://github.com/pygraphviz/pygraphviz.git
        pip install pygraphviz
        python -c "import pygraphviz; print(pygraphviz.__file__)"

        sudo pip3 install pygraphviz --install-option="--include-path=/usr/include/graphviz" --install-option="--library-path=/usr/lib/graphviz/"
        python3 -c "import pygraphviz; print(pygraphviz.__file__)"

    CommandLine:
        python -m ibeis.algo.hots.bayes --exec-show_model --show

    Example:
        >>> # DISABLE_DOCTEST
        >>> from ibeis.algo.hots.bayes import *  # NOQA
        >>> model = '?'
        >>> evidence = {}
        >>> soft_evidence = {}
        >>> result = show_model(model, evidence, soft_evidence)
        >>> print(result)
        >>> ut.quit_if_noshow()
        >>> import plottool as pt
        >>> ut.show_if_requested()
    """
    if ut.get_argval('--hackmarkov') or ut.get_argval('--hackjunc'):
        draw_tree_model(model, **kwargs)
        return

    import plottool as pt
    import networkx as netx
    fnum = pt.ensure_fnum(None)
    netx_graph = (model)
    #netx_graph.graph.setdefault('graph', {})['size'] = '"10,5"'
    #netx_graph.graph.setdefault('graph', {})['rankdir'] = 'LR'

    pos_dict = get_hacked_pos(netx_graph)
    #pos_dict = netx.nx_agraph.pygraphviz_layout(netx_graph)
    #pos = netx.nx_agraph.nx_pydot.pydot_layout(netx_graph, prog='dot')
    #pos_dict = netx.nx_agraph.graphviz_layout(netx_graph)

    textprops = {
        'family': 'monospace',
        'horizontalalignment': 'left',
        #'horizontalalignment': 'center',
        #'size': 12,
        'size': 8,
    }

    netx_nodes = model.nodes(data=True)
    node_key_list = ut.get_list_column(netx_nodes, 0)
    pos_list = ut.dict_take(pos_dict, node_key_list)

    var2_post = {f.variables[0]: f for f in kwargs.get('factor_list', [])}

    prior_text = None
    post_text = None
    evidence_tas = []
    post_tas = []
    prior_tas = []
    node_color = []

    has_inferred = evidence or var2_post
    if has_inferred:
        ignore_prior_with_ttype = [SCORE_TTYPE, MATCH_TTYPE]
        show_prior = False
    else:
        ignore_prior_with_ttype = []
        #show_prior = True
        show_prior = False

    dpy = 5
    dbx, dby = (20, 20)
    takw1 = {
        'bbox_align': (.5, 0),
        'pos_offset': [0, dpy],
        'bbox_offset': [dbx, dby]
    }
    takw2 = {
        'bbox_align': (.5, 1),
        'pos_offset': [0, -dpy],
        'bbox_offset': [-dbx, -dby]
    }

    name_colors = pt.distinct_colors(max(model.num_names, 10))
    name_colors = name_colors[:model.num_names]

    #cmap_ = 'hot' #mx = 0.65 #mn = 0.15
    cmap_, mn, mx = 'plasma', 0.15, 1.0
    _cmap = pt.plt.get_cmap(cmap_)

    def cmap(x):
        return _cmap((x * mx) + mn)

    for node, pos in zip(netx_nodes, pos_list):
        variable = node[0]
        cpd = model.var2_cpd[variable]
        prior_marg = (cpd if cpd.evidence is None else cpd.marginalize(
            cpd.evidence, inplace=False))

        show_evidence = variable in evidence
        show_prior = cpd.ttype not in ignore_prior_with_ttype
        show_post = variable in var2_post
        show_prior |= cpd.ttype not in ignore_prior_with_ttype

        post_marg = None

        if show_post:
            post_marg = var2_post[variable]

        def get_name_color(phi):
            order = phi.values.argsort()[::-1]
            if len(order) < 2:
                dist_next = phi.values[order[0]]
            else:
                dist_next = phi.values[order[0]] - phi.values[order[1]]
            dist_total = (phi.values[order[0]])
            confidence = (dist_total * dist_next)**(2.5 / 4)
            #print('confidence = %r' % (confidence,))
            color = name_colors[order[0]]
            color = pt.color_funcs.desaturate_rgb(color, 1 - confidence)
            color = np.array(color)
            return color

        if variable in evidence:
            if cpd.ttype == SCORE_TTYPE:
                cmap_index = evidence[variable] / (cpd.variable_card - 1)
                color = cmap(cmap_index)
                color = pt.lighten_rgb(color, .4)
                color = np.array(color)
                node_color.append(color)
            elif cpd.ttype == NAME_TTYPE:
                color = name_colors[evidence[variable]]
                color = np.array(color)
                node_color.append(color)
            else:
                color = pt.FALSE_RED
                node_color.append(color)
        #elif variable in soft_evidence:
        #    color = pt.LIGHT_PINK
        #    show_prior = True
        #    color = get_name_color(prior_marg)
        #    node_color.append(color)
        else:
            if cpd.ttype == NAME_TTYPE and post_marg is not None:
                color = get_name_color(post_marg)
                node_color.append(color)
            elif cpd.ttype == MATCH_TTYPE and post_marg is not None:
                color = cmap(post_marg.values[1])
                color = pt.lighten_rgb(color, .4)
                color = np.array(color)
                node_color.append(color)
            else:
                #color = pt.WHITE
                color = pt.NEUTRAL
                node_color.append(color)

        if show_prior:
            if variable in soft_evidence:
                prior_color = pt.LIGHT_PINK
            else:
                prior_color = None
            prior_text = pgm_ext.make_factor_text(prior_marg, 'prior')
            prior_tas.append(
                dict(text=prior_text, pos=pos, color=prior_color, **takw2))
        if show_evidence:
            _takw1 = takw1
            if cpd.ttype == SCORE_TTYPE:
                _takw1 = takw2
            evidence_text = cpd.variable_statenames[evidence[variable]]
            if isinstance(evidence_text, int):
                evidence_text = '%d/%d' % (evidence_text + 1,
                                           cpd.variable_card)
            evidence_tas.append(
                dict(text=evidence_text, pos=pos, color=color, **_takw1))
        if show_post:
            _takw1 = takw1
            if cpd.ttype == MATCH_TTYPE:
                _takw1 = takw2
            post_text = pgm_ext.make_factor_text(post_marg, 'post')
            post_tas.append(dict(text=post_text, pos=pos, color=None,
                                 **_takw1))

    def trnps_(dict_list):
        """ tranpose dict list """
        list_dict = ut.ddict(list)
        for dict_ in dict_list:
            for key, val in dict_.items():
                list_dict[key + '_list'].append(val)
        return list_dict

    takw1_ = trnps_(post_tas + evidence_tas)
    takw2_ = trnps_(prior_tas)

    # Draw graph
    if has_inferred:
        pnum1 = (3, 1, (slice(0, 2), 0))
    else:
        pnum1 = None

    fig = pt.figure(fnum=fnum, pnum=pnum1, doclf=True)  # NOQA
    ax = pt.gca()
    #print('node_color = %s' % (ut.repr3(node_color),))
    drawkw = dict(pos=pos_dict,
                  ax=ax,
                  with_labels=True,
                  node_size=1500,
                  node_color=node_color)
    netx.draw(netx_graph, **drawkw)

    hacks = []
    if len(post_tas + evidence_tas):
        hacks.append(pt.draw_text_annotations(textprops=textprops, **takw1_))
    if prior_tas:
        hacks.append(pt.draw_text_annotations(textprops=textprops, **takw2_))

    xmin, ymin = np.array(pos_list).min(axis=0)
    xmax, ymax = np.array(pos_list).max(axis=0)
    num_annots = len(model.ttype2_cpds[NAME_TTYPE])
    if num_annots > 4:
        ax.set_xlim((xmin - 40, xmax + 40))
        ax.set_ylim((ymin - 50, ymax + 50))
        fig.set_size_inches(30, 7)
    else:
        ax.set_xlim((xmin - 42, xmax + 42))
        ax.set_ylim((ymin - 50, ymax + 50))
        fig.set_size_inches(23, 7)
    fig = pt.gcf()

    title = 'num_names=%r, num_annots=%r' % (
        model.num_names,
        num_annots,
    )
    map_assign = kwargs.get('map_assign', None)

    top_assignments = kwargs.get('top_assignments', None)
    if top_assignments is not None:
        map_assign, map_prob = top_assignments[0]
        if map_assign is not None:

            def word_insert(text):
                return '' if len(text) == 0 else text + ' '

            title += '\n%sMAP: ' % (word_insert(kwargs.get('method', '')))
            title += map_assign + ' @' + '%.2f%%' % (100 * map_prob, )
    if kwargs.get('show_title', True):
        pt.set_figtitle(title, size=14)

    for hack in hacks:
        hack()

    # Hack in colorbars
    if has_inferred:
        pt.colorbar(np.linspace(0, 1, len(name_colors)),
                    name_colors,
                    lbl=NAME_TTYPE,
                    ticklabels=model.ttype2_template[NAME_TTYPE].basis,
                    ticklocation='left')

        basis = model.ttype2_template[SCORE_TTYPE].basis
        scalars = np.linspace(0, 1, len(basis))
        scalars = np.linspace(0, 1, 100)
        colors = pt.scores_to_color(scalars,
                                    cmap_=cmap_,
                                    reverse_cmap=False,
                                    cmap_range=(mn, mx))
        colors = [pt.lighten_rgb(c, .4) for c in colors]

        if ut.list_type(basis) is int:
            pt.colorbar(scalars,
                        colors,
                        lbl=SCORE_TTYPE,
                        ticklabels=np.array(basis) + 1)
        else:
            pt.colorbar(scalars, colors, lbl=SCORE_TTYPE, ticklabels=basis)
            #print('basis = %r' % (basis,))

    # Draw probability hist
    if has_inferred and top_assignments is not None:
        bin_labels = ut.get_list_column(top_assignments, 0)
        bin_vals = ut.get_list_column(top_assignments, 1)

        # bin_labels = ['\n'.join(ut.textwrap.wrap(_lbl, width=30)) for _lbl in bin_labels]

        pt.draw_histogram(
            bin_labels,
            bin_vals,
            fnum=fnum,
            pnum=(3, 8, (2, slice(4, None))),
            transpose=True,
            use_darkbackground=False,
            #xtick_rotation=-10,
            ylabel='Prob',
            xlabel='assignment')
        pt.set_title('Assignment probabilities')
Esempio n. 9
0
def show_multichip_match(rchip1, rchip2_list, kpts1, kpts2_list, fm_list,
                         fs_list, featflag_list, fnum=None, pnum=None,
                         **kwargs):
    """
    move to df2
    rchip = rchip1
    H = H1 = None
    target_wh = None

    """
    import vtool.image as gtool
    import plottool as pt
    import numpy as np
    import vtool as vt
    kwargs = kwargs.copy()

    colorbar_ = kwargs.pop('colorbar_', True)
    stack_larger = kwargs.pop('stack_larger', False)
    # mode for features disabled by name scoring
    NONVOTE_MODE = kwargs.get('nonvote_mode', 'filter')

    def preprocess_chips(rchip, H, target_wh):
        rchip_ = rchip if H is None else gtool.warpHomog(rchip, H, target_wh)
        return rchip_

    if fnum is None:
        fnum = pt.next_fnum()

    target_wh1 = None
    H1 = None
    rchip1_ = preprocess_chips(rchip1, H1, target_wh1)
    # Hack to visually identify the query
    rchip1_ = vt.draw_border(
        rchip1_, out=rchip1_, thickness=15,
        color=(pt.UNKNOWN_PURP[0:3] * 255).astype(np.uint8).tolist())
    wh1 = gtool.get_size(rchip1_)
    rchip2_list_ = [preprocess_chips(rchip2, None, wh1)
                    for rchip2 in rchip2_list]
    wh2_list = [gtool.get_size(rchip2) for rchip2 in rchip2_list_]

    num = 0 if len(rchip2_list) < 3 else 1
    #vert = True if len(rchip2_list) > 1 else False
    vert = True if len(rchip2_list) > 1 else None
    #num = 0

    if False and kwargs.get('fastmode', False):
        # This doesn't actually help the speed very much
        stackkw = dict(
            # Hack draw results faster Q
            #initial_sf=.4,
            #initial_sf=.9,
            use_larger=stack_larger,
            #use_larger=True,
        )
    else:
        stackkw = dict()
    #use_larger = True
    #vert = kwargs.get('fastmode', False)

    match_img, offset_list, sf_list = vt.stack_image_list_special(rchip1_,
                                                                  rchip2_list_,
                                                                  num=num,
                                                                  vert=vert,
                                                                  **stackkw)
    wh_list = np.array(ut.flatten([[wh1], wh2_list])) * sf_list

    offset1 = offset_list[0]
    wh1 = wh_list[0]
    sf1 = sf_list[0]

    fig, ax = pt.imshow(match_img, fnum=fnum, pnum=pnum)

    if kwargs.get('show_matches', True):
        ut.flatten(fs_list)
        #ut.embed()
        flat_fs, cumlen_list = ut.invertible_flatten2(fs_list)
        flat_colors = pt.scores_to_color(np.array(flat_fs), 'hot')
        colors_list = ut.unflatten2(flat_colors, cumlen_list)
        for _tup in zip(offset_list[1:], wh_list[1:], sf_list[1:], kpts2_list,
                        fm_list, fs_list, featflag_list, colors_list):
            offset2, wh2, sf2, kpts2, fm2_, fs2_, featflags, colors = _tup
            xywh1 = (offset1[0], offset1[1], wh1[0], wh1[1])
            xywh2 = (offset2[0], offset2[1], wh2[0], wh2[1])
            #colors = pt.scores_to_color(fs2)
            if kpts1 is not None and kpts2 is not None:
                if NONVOTE_MODE == 'filter':
                    fm2 = fm2_.compress(featflags, axis=0)
                    fs2 = fs2_.compress(featflags, axis=0)
                elif NONVOTE_MODE == 'only':
                    fm2 = fm2_.compress(np.logical_not(featflags), axis=0)
                    fs2 = fs2_.compress(np.logical_not(featflags), axis=0)
                else:
                    # TODO: optional coloring of nonvotes instead
                    fm2 = fm2_
                    fs2 = fs2_
                pt.plot_fmatch(xywh1, xywh2, kpts1, kpts2, fm2, fs2,
                               fm_norm=None, H1=None, H2=None,
                               scale_factor1=sf1, scale_factor2=sf2,
                               colorbar_=False, colors=colors, **kwargs)
        if colorbar_:
            pt.colorbar(flat_fs, flat_colors)
    bbox_list = [(x, y, w, h) for (x, y), (w, h) in zip(offset_list, wh_list)]
    return offset_list, sf_list, bbox_list
Esempio n. 10
0
def show_chip(ibs, aid, in_image=False, annote=True, title_suffix='',
                weight_label=None, weights=None, config2_=None, **kwargs):
    r""" Driver function to show chips

    Args:
        ibs (ibeis.IBEISController):
        aid (int): annotation rowid
        in_image (bool): displays annotation with the context of its source image
        annote (bool): enables overlay annoations
        title_suffix (str):
        weight_label (None): (default = None)
        weights (None): (default = None)
        config2_ (dict): (default = None)

    Kwargs:
        enable_chip_title_prefix, nokpts, kpts_subset, kpts, text_color,
        notitle, draw_lbls, show_aidstr, show_gname, show_name, show_nid,
        show_exemplar, show_num_gt, show_quality_text, show_yawtext, fnum,
        title, figtitle, pnum, interpolation, cmap, heatmap, data_colorbar,
        darken, update, xlabel, redraw_image, ax, alpha, docla, doclf,
        projection, use_gridspec, pts, ell
        color (3/4-tuple, ndarray, or str): colors for keypoints

    CommandLine:
        python -m ibeis.viz.viz_chip --test-show_chip --show --ecc
        python -c "import utool as ut; ut.print_auto_docstr('ibeis.viz.viz_chip', 'show_chip')"
        python -m ibeis.viz.viz_chip --test-show_chip --show --db NNP_Master3 --aids 14047 --no-annote
        python -m ibeis.viz.viz_chip --test-show_chip --show --db NNP_Master3 --aids 14047 --no-annote

        python -m ibeis.viz.viz_chip --test-show_chip --show --db PZ_MTEST --aid 1 --bgmethod=cnn
        python -m ibeis.viz.viz_chip --test-show_chip --show --db PZ_MTEST --aid 1 --bgmethod=cnn --scale_max=30

    Example:
        >>> # VIZ_TEST
        >>> from ibeis.viz.viz_chip import *  # NOQA
        >>> import numpy as np
        >>> import vtool as vt
        >>> in_image = False
        >>> ibs, aid_list, kwargs, config2_ = testdata_showchip()
        >>> aid = aid_list[0]
        >>> if ut.get_argflag('--ecc'):
        >>>     kpts = ibs.get_annot_kpts(aid, config2_=config2_)
        >>>     weights = ibs.get_annot_fgweights([aid], ensure=True, config2_=config2_)[0]
        >>>     kpts = ut.random_sample(kpts[weights > .9], 200, seed=0)
        >>>     ecc = vt.get_kpts_eccentricity(kpts)
        >>>     scale = 1 / vt.get_scales(kpts)
        >>>     s = ecc if config2_.affine_invariance else scale
        >>>     colors = pt.scores_to_color(s, cmap_='jet')
        >>>     kwargs['color'] = colors
        >>>     kwargs['kpts'] = kpts
        >>> show_chip(ibs, aid, in_image=in_image, config2_=config2_, **kwargs)
        >>> pt.show_if_requested()
    """
    if ut.VERBOSE:
        print('[viz] show_chip(aid=%r)' % (aid,))
    #ibs.assert_valid_aids((aid,))
    # Get chip
    #print('in_image = %r' % (in_image,))
    chip = vh.get_chips(ibs, aid, in_image=in_image, config2_=config2_)
    # Create chip title
    chip_text = vh.get_annot_texts(ibs, [aid], **kwargs)[0]
    if kwargs.get('enable_chip_title_prefix', True):
        chip_title_text = chip_text + title_suffix
    else:
        chip_title_text = title_suffix
    chip_title_text = chip_title_text.strip('\n')
    # Draw chip
    fig, ax = pt.imshow(chip, **kwargs)
    # Populate axis user data
    vh.set_ibsdat(ax, 'viztype', 'chip')
    vh.set_ibsdat(ax, 'aid', aid)
    if annote and not kwargs.get('nokpts', False):
        # Get and draw keypoints
        if 'color' not in kwargs:
            if weight_label == 'fg_weights':
                if weights is None and ibs.has_species_detector(ibs.get_annot_species_texts(aid)):
                    weight_label = 'fg_weights'
                    weights = ibs.get_annot_fgweights([aid], ensure=True, config2_=config2_)[0]
            if weights is not None:
                cmap_ = 'hot'
                #if weight_label == 'dstncvs':
                #    cmap_ = 'rainbow'
                color = pt.scores_to_color(weights, cmap_=cmap_, reverse_cmap=False)
                kwargs['color'] = color
                kwargs['ell_color'] = color
                kwargs['pts_color'] = color

        kpts_ = vh.get_kpts(ibs, aid, in_image, config2_=config2_,
                            kpts_subset=kwargs.get('kpts_subset', None),
                            kpts=kwargs.get('kpts', None))
        try:
            del kwargs['kpts']
        except KeyError:
            pass
        pt.viz_keypoints._annotate_kpts(kpts_, **kwargs)
        if not ut.get_argflag('--noaidlabel'):
            pt.upperleft_text(chip_text, color=kwargs.get('text_color', None))
    use_title = not kwargs.get('notitle', False)
    if use_title:
        pt.set_title(chip_title_text)
    if in_image:
        gid = ibs.get_annot_gids(aid)
        aid_list = ibs.get_image_aids(gid)
        annotekw = viz_image.get_annot_annotations(
            ibs, aid_list, sel_aids=[aid], draw_lbls=kwargs.get('draw_lbls', True))
        # Put annotation centers in the axis
        ph.set_plotdat(ax, 'annotation_bbox_list', annotekw['bbox_list'])
        ph.set_plotdat(ax, 'aid_list', aid_list)
        pt.viz_image2.draw_image_overlay(ax, **annotekw)

        zoom_ = ut.get_argval('--zoom', type_=float, default=None)
        if zoom_ is not None:
            import vtool as vt
            # Zoom into the chip for some image context
            rotated_verts = ibs.get_annot_rotated_verts(aid)
            bbox = ibs.get_annot_bboxes(aid)
            #print(bbox)
            #print(rotated_verts)
            rotated_bbox = vt.bbox_from_verts(rotated_verts)
            imgw, imgh = ibs.get_image_sizes(gid)

            pad_factor = zoom_
            pad_length = min(bbox[2], bbox[3]) * pad_factor
            minx = max(rotated_bbox[0] - pad_length, 0)
            miny = max(rotated_bbox[1] - pad_length, 0)
            maxx = min((rotated_bbox[0] + rotated_bbox[2]) + pad_length, imgw)
            maxy = min((rotated_bbox[1] + rotated_bbox[3]) + pad_length, imgh)

            #maxy = imgh - maxy
            #miny = imgh - miny

            ax = pt.gca()
            ax.set_xlim(minx, maxx)
            ax.set_ylim(miny, maxy)
            ax.invert_yaxis()
    else:
        ph.set_plotdat(ax, 'chipshape', chip.shape)

    #if 'featweights' in vars() and 'color' in kwargs:
    if weights is not None and weight_label is not None:
        ## HACK HACK HACK
        if len(weights) > 0:
            cb = pt.colorbar(weights, kwargs['color'])
            cb.set_label(weight_label)
    return fig, ax
Esempio n. 11
0
    def initialize_graph_and_model(infr):
        """ Unused in internal split stuff

        pt.qt4ensure()
        layout_info = pt.show_nx(graph, as_directed=False, fnum=1,
                                 layoutkw=dict(prog='neato'), use_image=True,
                                 verbose=0)
        ax = pt.gca()
        pt.zoom_factory()
        pt.interactions.PanEvents()
        """
        #import networkx as nx
        #import itertools
        cm_list = infr.cm_list
        hack = True
        hack = False
        if hack:
            cm_list = cm_list[:10]
        qaid_list = [cm.qaid for cm in cm_list]
        daids_list = [cm.daid_list for cm in cm_list]
        unique_aids = sorted(ut.list_union(*daids_list + [qaid_list]))
        if hack:
            unique_aids = sorted(ut.isect(unique_aids, qaid_list))
        aid2_aidx = ut.make_index_lookup(unique_aids)

        # Construct K-broken graph
        edges = []
        edge_weights = []
        #top = (infr.qreq_.qparams.K + 1) * 2
        #top = (infr.qreq_.qparams.K) * 2
        top = (infr.qreq_.qparams.K + 2)
        for count, cm in enumerate(cm_list):
            qidx = aid2_aidx[cm.qaid]
            score_list = cm.annot_score_list
            sortx = ut.argsort(score_list)[::-1]
            score_list = ut.take(score_list, sortx)[:top]
            daid_list = ut.take(cm.daid_list, sortx)[:top]
            for score, daid in zip(score_list, daid_list):
                if daid not in qaid_list:
                    continue
                didx = aid2_aidx[daid]
                edge_weights.append(score)
                edges.append((qidx, didx))

        # make symmetric
        directed_edges = dict(zip(edges, edge_weights))
        # Find edges that point in both directions
        undirected_edges = {}
        for (u, v), w in directed_edges.items():
            if (v, u) in undirected_edges:
                undirected_edges[(v, u)] += w
                undirected_edges[(v, u)] /= 2
            else:
                undirected_edges[(u, v)] = w

        edges = list(undirected_edges.keys())
        edge_weights = list(undirected_edges.values())
        nodes = list(range(len(unique_aids)))

        nid_labeling = infr.qreq_.ibs.get_annot_nids(unique_aids)
        labeling = ut.rebase_labels(nid_labeling)

        import networkx as nx
        from ibeis.viz import viz_graph
        set_node_attrs = nx.set_node_attributes
        set_edge_attrs = nx.set_edge_attributes

        # Create match-based graph structure
        graph = nx.DiGraph()
        graph.add_nodes_from(nodes)
        graph.add_edges_from(edges)

        # Important properties
        nid_list = infr.qreq_.ibs.get_annot_nids(unique_aids)
        labeling = ut.rebase_labels(nid_list)

        set_node_attrs(graph, 'name_label', dict(zip(nodes, labeling)))
        set_edge_attrs(graph, 'weight', dict(zip(edges, edge_weights)))

        # Visualization properties
        import plottool as pt
        ax2_aid = ut.invert_dict(aid2_aidx)
        set_node_attrs(graph, 'aid', ax2_aid)
        viz_graph.ensure_node_images(infr.qreq_.ibs, graph)
        set_node_attrs(graph, 'framewidth', dict(zip(nodes, [3.0] * len(nodes))))
        set_node_attrs(graph, 'framecolor', dict(zip(nodes, [pt.DARK_BLUE] * len(nodes))))
        ut.color_nodes(graph, labelattr='name_label')

        edge_colors = pt.scores_to_color(np.array(edge_weights), cmap_='viridis')
        #import utool
        #utool.embed()
        #edge_colors = [pt.color_funcs.ensure_base255(color) for color in edge_colors]
        #print('edge_colors = %r' % (edge_colors,))
        set_edge_attrs(graph, 'color', dict(zip(edges, edge_colors)))

        # Build inference model
        from ibeis.algo.hots import graph_iden
        #graph_iden.rrr()
        model = graph_iden.InfrModel(graph)
        #model = graph_iden.InfrModel(len(nodes), edges, edge_weights, labeling=labeling)
        infr.model = model