Python matplotlib.cm.get_cmap() Examples

The following are 30 code examples for showing how to use matplotlib.cm.get_cmap(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module matplotlib.cm , or try the search function .

Example 1
Project: keras-anomaly-detection   Author: chen0040   File: h2o_ecg_pulse_detection.py    License: MIT License 6 votes vote down vote up
def plot_bidimensional(model, test, recon_error, layer, title):
    bidimensional_data = model.deepfeatures(test, layer).cbind(recon_error).as_data_frame()

    cmap = cm.get_cmap('Spectral')

    fig, ax = plt.subplots()
    bidimensional_data.plot(kind='scatter',
                            x='DF.L{}.C1'.format(layer + 1),
                            y='DF.L{}.C2'.format(layer + 1),
                            s=500,
                            c='Reconstruction.MSE',
                            title=title,
                            ax=ax,
                            colormap=cmap)
    layer_column = 'DF.L{}.C'.format(layer + 1)
    columns = [layer_column + '1', layer_column + '2']
    for k, v in bidimensional_data[columns].iterrows():
        ax.annotate(k, v, size=20, verticalalignment='bottom', horizontalalignment='left')
    fig.canvas.draw()
    plt.show() 
Example 2
Project: kvae   Author: simonkamronn   File: plotting.py    License: MIT License 6 votes vote down vote up
def construct_ball_trajectory(var, r=1., cmap='Blues', start_color=0.4, shape='c'):
    # https://matplotlib.org/examples/color/colormaps_reference.html
    patches = []
    for pos in var:
        if shape == 'c':
            patches.append(mpatches.Circle(pos, r))
        elif shape == 'r':
            patches.append(mpatches.RegularPolygon(pos, 4, r))
        elif shape == 's':
            patches.append(mpatches.RegularPolygon(pos, 6, r))

    colors = np.linspace(start_color, .9, len(patches))
    collection = PatchCollection(patches, cmap=cm.get_cmap(cmap), alpha=1.)
    collection.set_array(np.array(colors))
    collection.set_clim(0, 1)
    return collection 
Example 3
Project: deep-smoke-machine   Author: CMU-CREATE-Lab   File: viz_functional.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def apply_colormap_on_image(org_im, activation, colormap_name):
    """
        Apply heatmap on image
    Args:
        org_img (PIL img): Original image
        activation_map (numpy arr): Activation map (grayscale) 0-255
        colormap_name (str): Name of the colormap
    """
    # Get colormap
    color_map = mpl_color_map.get_cmap(colormap_name)
    no_trans_heatmap = color_map(activation)

    # Change alpha channel in colormap to make sure original image is displayed
    heatmap = copy.copy(no_trans_heatmap)
    heatmap[:, :, 3] = 0.4
    heatmap = Image.fromarray((heatmap*255).astype(np.uint8))
    no_trans_heatmap = Image.fromarray((no_trans_heatmap*255).astype(np.uint8))

    # Apply heatmap on image
    heatmap_on_image = Image.new("RGBA", org_im.size)
    heatmap_on_image = Image.alpha_composite(heatmap_on_image, org_im.convert('RGBA'))
    heatmap_on_image = Image.alpha_composite(heatmap_on_image, heatmap)
    return no_trans_heatmap, heatmap_on_image 
Example 4
Project: LSDMappingTools   Author: LSDtopotools   File: colours.py    License: MIT License 6 votes vote down vote up
def list_of_hex_colours(N, base_cmap):
    """
    Return a list of colors from a colourmap as hex codes

        Arguments:
            cmap: colormap instance, eg. cm.jet.
            N: number of colors.

        Author: FJC
    """
    cmap = _cm.get_cmap(base_cmap, N)

    hex_codes = []
    for i in range(cmap.N):
        rgb = cmap(i)[:3] # will return rgba, we take only first 3 so we get rgb
        hex_codes.append(_mcolors.rgb2hex(rgb))
    return hex_codes 
Example 5
Project: LSDMappingTools   Author: LSDtopotools   File: colours.py    License: MIT License 6 votes vote down vote up
def cmap_discretize(N, cmap):
    """Return a discrete colormap from the continuous colormap cmap.

    Arguments:
        cmap: colormap instance, eg. cm.jet.
        N: number of colors.

    Example:
        x = resize(arange(100), (5,100))
        djet = cmap_discretize(cm.jet, 5)
        imshow(x, cmap=djet)
    """

    if type(cmap) == str:
        cmap = _plt.get_cmap(cmap)
    colors_i = _np.concatenate((_np.linspace(0, 1., N), (0.,0.,0.,0.)))
    colors_rgba = cmap(colors_i)
    indices = _np.linspace(0, 1., N+1)
    cdict = {}
    for ki,key in enumerate(('red','green','blue')):
        cdict[key] = [ (indices[i], colors_rgba[i-1,ki], colors_rgba[i,ki])
                       for i in range(N+1) ]
    # Return colormap object.
    return _mcolors.LinearSegmentedColormap(cmap.name + "_%d"%N, cdict, 1024) 
Example 6
Project: LSDMappingTools   Author: LSDtopotools   File: colours.py    License: MIT License 6 votes vote down vote up
def __init__(self, cmap, levels):

        if isinstance(cmap, str):
            self.cmap = _cm.get_cmap(cmap)
        elif isinstance(cmap, _mcolors.Colormap):
            self.cmap = cmap
        else:
            raise ValueError('Colourmap must either be a string name of a colormap, \
                         or a Colormap object (class instance). Please try again.' \
                         "Colourmap supplied is of type: ", type(cmap))

        self.N = self.cmap.N
        self.monochrome = self.cmap.monochrome
        self.levels = _np.asarray(levels)#, dtype='float64')
        self._x = self.levels
        self.levmax = self.levels.max()
        self.levmin = self.levels.min()
        self.transformed_levels = _np.linspace(self.levmin, self.levmax,
             len(self.levels)) 
Example 7
Project: defragTrees   Author: sato9hara   File: paper_synthetic2.py    License: MIT License 6 votes vote down vote up
def plotTZ(filename=None):
    t = np.linspace(0, 1, 101)
    z = 0.25 + 0.5 / (1 + np.exp(- 20 * (t - 0.5))) + 0.05 * np.cos(t * 2 * np.pi)
    cmap = cm.get_cmap('cool')
    fig, (ax1, ax2) = plt.subplots(1, 2, gridspec_kw = {'width_ratios':[19, 1]})
    poly1 = [[0, 0]]
    poly1.extend([[t[i], z[i]] for i in range(t.size)])
    poly1.extend([[1, 0], [0, 0]])
    poly2 = [[0, 1]]
    poly2.extend([[t[i], z[i]] for i in range(t.size)])
    poly2.extend([[1, 1], [0, 1]])
    poly1 = plt.Polygon(poly1,fc=cmap(0.0))
    poly2 = plt.Polygon(poly2,fc=cmap(1.0))
    ax1.add_patch(poly1)
    ax1.add_patch(poly2)
    ax1.set_xlabel('x1', size=22)
    ax1.set_ylabel('x2', size=22)
    ax1.set_title('True Data', size=28)
    colorbar.ColorbarBase(ax2, cmap=cmap, format='%.1f')
    ax2.set_ylabel('Output y', size=22)
    plt.show()
    if not filename is None:
        plt.savefig(filename, format="pdf", bbox_inches="tight")
        plt.close() 
Example 8
Project: defragTrees   Author: sato9hara   File: paper_synthetic1.py    License: MIT License 6 votes vote down vote up
def plotTZ(filename=None):
    cmap = cm.get_cmap('cool')
    fig, (ax1, ax2) = plt.subplots(1, 2, gridspec_kw = {'width_ratios':[19, 1]})
    ax1.add_patch(pl.Rectangle(xy=[0, 0], width=0.5, height=0.5, facecolor=cmap(0.0), linewidth='2.0'))
    ax1.add_patch(pl.Rectangle(xy=[0.5, 0.5], width=0.5, height=0.5, facecolor=cmap(0.0), linewidth='2.0'))
    ax1.add_patch(pl.Rectangle(xy=[0, 0.5], width=0.5, height=0.5, facecolor=cmap(1.0), linewidth='2.0'))
    ax1.add_patch(pl.Rectangle(xy=[0.5, 0], width=0.5, height=0.5, facecolor=cmap(1.0), linewidth='2.0'))
    ax1.set_xlabel('x1', size=22)
    ax1.set_ylabel('x2', size=22)
    ax1.set_title('True Data', size=28)
    colorbar.ColorbarBase(ax2, cmap=cmap, format='%.1f')
    ax2.set_ylabel('Output y', size=22)
    plt.show()
    if not filename is None:
        plt.savefig(filename, format="pdf", bbox_inches="tight")
        plt.close() 
Example 9
Project: Computable   Author: ktraunmueller   File: pyplot.py    License: MIT License 6 votes vote down vote up
def set_cmap(cmap):
    """
    Set the default colormap.  Applies to the current image if any.
    See help(colormaps) for more information.

    *cmap* must be a :class:`~matplotlib.colors.Colormap` instance, or
    the name of a registered colormap.

    See :func:`matplotlib.cm.register_cmap` and
    :func:`matplotlib.cm.get_cmap`.
    """
    cmap = cm.get_cmap(cmap)

    rc('image', cmap=cmap.name)
    im = gci()

    if im is not None:
        im.set_cmap(cmap)

    draw_if_interactive() 
Example 10
Project: Computable   Author: ktraunmueller   File: colorbar.py    License: MIT License 6 votes vote down vote up
def colorbar(mappable, cax=None, ax=None, **kw):
    """
    Create a colorbar for a ScalarMappable instance.

    Documentation for the pylab thin wrapper:
    %(colorbar_doc)s
    """
    import matplotlib.pyplot as plt
    if ax is None:
        ax = plt.gca()
    if cax is None:
        cax, kw = make_axes(ax, **kw)
    cax.hold(True)
    cb = Colorbar(cax, mappable, **kw)

    def on_changed(m):
        cb.set_cmap(m.get_cmap())
        cb.set_clim(m.get_clim())
        cb.update_bruteforce(m)

    cbid = mappable.callbacksSM.connect('changed', on_changed)
    mappable.colorbar = cb
    ax.figure.sca(ax)
    return cb 
Example 11
Project: Computable   Author: ktraunmueller   File: colorbar.py    License: MIT License 6 votes vote down vote up
def colorbar(mappable, cax=None, ax=None, **kw):
    """
    Create a colorbar for a ScalarMappable instance.

    Documentation for the pylab thin wrapper:
    %(colorbar_doc)s
    """
    import matplotlib.pyplot as plt
    if ax is None:
        ax = plt.gca()
    if cax is None:
        cax, kw = make_axes(ax, **kw)
    cax.hold(True)
    cb = Colorbar(cax, mappable, **kw)

    def on_changed(m):
        cb.set_cmap(m.get_cmap())
        cb.set_clim(m.get_clim())
        cb.update_bruteforce(m)

    cbid = mappable.callbacksSM.connect('changed', on_changed)
    mappable.colorbar = cb
    ax.figure.sca(ax)
    return cb 
Example 12
Project: matplotlib-4-abaqus   Author: Solid-Mechanics   File: pyplot.py    License: MIT License 6 votes vote down vote up
def set_cmap(cmap):
    """
    Set the default colormap.  Applies to the current image if any.
    See help(colormaps) for more information.

    *cmap* must be a :class:`~matplotlib.colors.Colormap` instance, or
    the name of a registered colormap.

    See :func:`matplotlib.cm.register_cmap` and
    :func:`matplotlib.cm.get_cmap`.
    """
    cmap = cm.get_cmap(cmap)

    rc('image', cmap=cmap.name)
    im = gci()

    if im is not None:
        im.set_cmap(cmap)

    draw_if_interactive() 
Example 13
Project: matplotlib-4-abaqus   Author: Solid-Mechanics   File: colorbar.py    License: MIT License 6 votes vote down vote up
def colorbar(mappable, cax=None, ax=None, **kw):
    """
    Create a colorbar for a ScalarMappable instance.

    Documentation for the pylab thin wrapper:
    %(colorbar_doc)s
    """
    import matplotlib.pyplot as plt
    if ax is None:
        ax = plt.gca()
    if cax is None:
        cax, kw = make_axes(ax, **kw)
    cax.hold(True)
    cb = Colorbar(cax, mappable, **kw)

    def on_changed(m):
        cb.set_cmap(m.get_cmap())
        cb.set_clim(m.get_clim())
        cb.update_bruteforce(m)

    cbid = mappable.callbacksSM.connect('changed', on_changed)
    mappable.colorbar = cb
    ax.figure.sca(ax)
    return cb 
Example 14
Project: matplotlib-4-abaqus   Author: Solid-Mechanics   File: colorbar.py    License: MIT License 6 votes vote down vote up
def colorbar(mappable, cax=None, ax=None, **kw):
    """
    Create a colorbar for a ScalarMappable instance.

    Documentation for the pylab thin wrapper:
    %(colorbar_doc)s
    """
    import matplotlib.pyplot as plt
    if ax is None:
        ax = plt.gca()
    if cax is None:
        cax, kw = make_axes(ax, **kw)
    cax.hold(True)
    cb = Colorbar(cax, mappable, **kw)

    def on_changed(m):
        cb.set_cmap(m.get_cmap())
        cb.set_clim(m.get_clim())
        cb.update_bruteforce(m)

    cbid = mappable.callbacksSM.connect('changed', on_changed)
    mappable.colorbar = cb
    ax.figure.sca(ax)
    return cb 
Example 15
Project: neural-network-animation   Author: miloharper   File: test_colorbar.py    License: MIT License 6 votes vote down vote up
def _get_cmap_norms():
    """
    Define a colormap and appropriate norms for each of the four
    possible settings of the extend keyword.

    Helper function for _colorbar_extension_shape and
    colorbar_extension_length.
    """
    # Create a color map and specify the levels it represents.
    cmap = get_cmap("RdBu", lut=5)
    clevs = [-5., -2.5, -.5, .5, 1.5, 3.5]
    # Define norms for the color maps.
    norms = dict()
    norms['neither'] = BoundaryNorm(clevs, len(clevs) - 1)
    norms['min'] = BoundaryNorm([-10] + clevs[1:], len(clevs) - 1)
    norms['max'] = BoundaryNorm(clevs[:-1] + [10], len(clevs) - 1)
    norms['both'] = BoundaryNorm([-10] + clevs[1:-1] + [10], len(clevs) - 1)
    return cmap, norms 
Example 16
Project: oggm   Author: OGGM   File: graphics.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def set_oggm_cmaps(use_hcl=None):
    # Set global colormaps
    global OGGM_CMAPS

    if use_hcl is None:
        use_hcl = HAS_HCL_CMAP

    OGGM_CMAPS['terrain'] = colormap.terrain
    if HAS_HCL_CMAP and use_hcl:
        cm_divs = 100  # number of discrete colours from continuous colormaps
        tcmap = sequential_hcl("Blue-Yellow", rev=True).cmap(cm_divs)
        OGGM_CMAPS['section_thickness'] = tcmap
        OGGM_CMAPS['glacier_thickness'] = tcmap
    else:
        OGGM_CMAPS['section_thickness'] = plt.cm.get_cmap('YlOrRd')
        OGGM_CMAPS['glacier_thickness'] = plt.get_cmap('viridis') 
Example 17
Project: MDT   Author: robbert-harms   File: matplotlib_renderer.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def _get_map_plot_options(self, map_name):
        cmap = get_cmap(self._get_map_attr(map_name, 'colormap', self._plot_config.colormap))

        masked_color = self._get_map_attr(map_name, 'colormap_masked_color', self._plot_config.colormap_masked_color)
        if masked_color is not None:
            cmap.set_bad(color=masked_color)

        output_dict = {'vmin': self._data_info.get_single_map_info(map_name).min(),
                       'vmax': self._data_info.get_single_map_info(map_name).max(),
                       'cmap': cmap}

        scale = self._get_map_attr(map_name, 'scale', Scale())
        if scale.use_max:
            output_dict['vmax'] = scale.vmax
        if scale.use_min:
            output_dict['vmin'] = scale.vmin

        return output_dict 
Example 18
Project: GraphicDesignPatternByPython   Author: Relph1119   File: pyplot.py    License: MIT License 6 votes vote down vote up
def set_cmap(cmap):
    """
    Set the default colormap.  Applies to the current image if any.
    See help(colormaps) for more information.

    *cmap* must be a :class:`~matplotlib.colors.Colormap` instance, or
    the name of a registered colormap.

    See :func:`matplotlib.cm.register_cmap` and
    :func:`matplotlib.cm.get_cmap`.
    """
    cmap = cm.get_cmap(cmap)

    rc('image', cmap=cmap.name)
    im = gci()

    if im is not None:
        im.set_cmap(cmap) 
Example 19
Project: GraphicDesignPatternByPython   Author: Relph1119   File: colorbar.py    License: MIT License 6 votes vote down vote up
def colorbar(mappable, cax=None, ax=None, **kw):
    """
    Create a colorbar for a ScalarMappable instance.

    Documentation for the pyplot thin wrapper:

    %s
    """
    import matplotlib.pyplot as plt
    if ax is None:
        ax = plt.gca()
    if cax is None:
        cax, kw = make_axes(ax, **kw)
    cb = Colorbar(cax, mappable, **kw)

    def on_changed(m):
        cb.set_cmap(m.get_cmap())
        cb.set_clim(m.get_clim())
        cb.update_bruteforce(m)

    cbid = mappable.callbacksSM.connect('changed', on_changed)
    mappable.colorbar = cb
    ax.figure.sca(ax)
    return cb 
Example 20
Project: xcube   Author: dcs4cop   File: test_cmaps.py    License: MIT License 6 votes vote down vote up
def test_get_cmap(self):
        ensure_cmaps_loaded()

        cmap_name, cmap = get_cmap('plasma')
        self.assertEqual('plasma', cmap_name)
        self.assertIsInstance(cmap, Colormap)

        cmap_name, cmap = get_cmap('PLASMA')
        self.assertEqual('viridis', cmap_name)
        self.assertIsInstance(cmap, Colormap)

        cmap_name, cmap = get_cmap('PLASMA', default_cmap_name='magma')
        self.assertEqual('magma', cmap_name)
        self.assertIsInstance(cmap, Colormap)

        with self.assertRaises(ValueError):
            get_cmap('PLASMA', default_cmap_name='MAGMA') 
Example 21
Project: mindpark   Author: danijar   File: metrics.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _process_metric(self, ax, metric):
        if not metric.data.size:
            ax.tick_params(colors=(0, 0, 0, 0))
            ax.set_axis_bgcolor(cm.get_cmap('viridis')(0))
            divider = make_axes_locatable(ax)
            divider.append_axes('right', size='7%', pad=0.1).axis('off')
            return
        domain = self._domain(metric)
        categorical = self._is_categorical(metric.data)
        if metric.data.shape[1] == 1 and not categorical:
            self._plot_scalar(ax, domain, metric.data[:, 0])
        elif metric.data.shape[1] == 1:
            indices = metric.data[:, 0].astype(int)
            min_, max_ = indices.min(), indices.max()
            count = np.eye(max_ - min_ + 1)[indices - min_]
            self._plot_distribution(ax, domain, count)
        elif metric.data.shape[1] > 1:
            self._plot_counts(ax, domain, metric.data) 
Example 22
Project: python3_ios   Author: holzschu   File: test_colorbar.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_colorbar_closed_patch():
    fig = plt.figure(figsize=(8, 6))
    ax1 = fig.add_axes([0.05, 0.85, 0.9, 0.1])
    ax2 = fig.add_axes([0.1, 0.65, 0.75, 0.1])
    ax3 = fig.add_axes([0.05, 0.45, 0.9, 0.1])
    ax4 = fig.add_axes([0.05, 0.25, 0.9, 0.1])
    ax5 = fig.add_axes([0.05, 0.05, 0.9, 0.1])

    cmap = get_cmap("RdBu", lut=5)

    im = ax1.pcolormesh(np.linspace(0, 10, 16).reshape((4, 4)), cmap=cmap)
    values = np.linspace(0, 10, 5)

    with rc_context({'axes.linewidth': 16}):
        plt.colorbar(im, cax=ax2, cmap=cmap, orientation='horizontal',
                     extend='both', extendfrac=0.5, values=values)
        plt.colorbar(im, cax=ax3, cmap=cmap, orientation='horizontal',
                     extend='both', values=values)
        plt.colorbar(im, cax=ax4, cmap=cmap, orientation='horizontal',
                     extend='both', extendrect=True, values=values)
        plt.colorbar(im, cax=ax5, cmap=cmap, orientation='horizontal',
                     extend='neither', values=values) 
Example 23
Project: python3_ios   Author: holzschu   File: pyplot.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def set_cmap(cmap):
    """
    Set the default colormap.  Applies to the current image if any.
    See help(colormaps) for more information.

    *cmap* must be a :class:`~matplotlib.colors.Colormap` instance, or
    the name of a registered colormap.

    See :func:`matplotlib.cm.register_cmap` and
    :func:`matplotlib.cm.get_cmap`.
    """
    cmap = cm.get_cmap(cmap)

    rc('image', cmap=cmap.name)
    im = gci()

    if im is not None:
        im.set_cmap(cmap) 
Example 24
Project: safepy   Author: baryshnikova-lab   File: safe_colormaps.py    License: GNU General Public License v3.0 6 votes vote down vote up
def get_colors(colormap='hsv', n=10):

    cmap = cm.get_cmap(colormap)

    # First color, always black
    rgb = [(0, 0, 0, 1)]

    for c in np.arange(1, n):
        rgb.append(cmap(c/n))

    rgb = np.asarray(rgb)

    # Randomize the other colors
    np.random.shuffle(rgb[1:])

    return rgb 
Example 25
Project: NucleoATAC   Author: GreenleafLab   File: chunkmat2d.py    License: MIT License 6 votes vote down vote up
def plot(self, filename = None, title = None, lower = None,
             upper = None):
        """Plot 2d ReadMat"""
        if upper is None:
            upper = self.upper
        if lower is None:
            lower = self.lower
        fig = plt.figure()
        plt.imshow(self.get(lower= lower, upper = upper),
                   origin="lower",interpolation='nearest',
                extent=[self.start,self.end-1,lower,upper-1],cmap=cm.get_cmap('Greys'))
        plt.xlabel(self.chrom)
        plt.ylabel("Insert size")
        if title:
            plt.title(title)
        #plt.colorbar(shrink=0.8)
        if filename:
            fig.savefig(filename)
            plt.close(fig)
            #Also save text output!
            filename2 = ".".join(filename.split(".")[:-1]+['txt'])
            np.savetxt(filename2,self.mat,delimiter="\t")
        else:
            fig.show() 
Example 26
Project: scanorama   Author: brianhie   File: utils.py    License: MIT License 5 votes vote down vote up
def visualize_expr(X, coords, genes, viz_gene, image_suffix='.svg',
                   new_fig=True, size=1, viz_prefix='ve'):
    genes = [ gene.upper() for gene in genes ]
    viz_gene = viz_gene.upper()

    if not viz_gene.upper() in genes:
        sys.stderr.write('Warning: Could not find gene {}\n'.format(viz_gene))
        return

    image_fname = '{}_{}{}'.format(
        viz_prefix, viz_gene, image_suffix
    )

    # Color based on percentiles.
    x_gene = X[:, list(genes).index(viz_gene)].toarray()
    colors = np.zeros(x_gene.shape)
    n_tiles = 100
    prev_percentile = min(x_gene)
    for i in range(n_tiles):
        q = (i+1) / float(n_tiles) * 100.
        percentile = np.percentile(x_gene, q)
        idx = np.logical_and(prev_percentile <= x_gene,
                             x_gene <= percentile)
        colors[idx] = i
        prev_percentile = percentile

    colors = colors.flatten()

    if new_fig:
        plt.figure()
        plt.title(viz_gene)
    plt.scatter(coords[:, 0], coords[:, 1],
                c=colors, cmap=cm.get_cmap('Reds'), s=size)
    plt.savefig(image_fname, dpi=500) 
Example 27
Project: scanorama   Author: brianhie   File: utils.py    License: MIT License 5 votes vote down vote up
def visualize_dropout(X, coords, image_suffix='.svg',
                      new_fig=True, size=1, viz_prefix='dropout'):
    image_fname = '{}{}'.format(
        viz_prefix, image_suffix
    )

    # Color based on percentiles.
    x_gene = np.array(np.sum(X != 0, axis=1))
    colors = np.zeros(x_gene.shape)
    n_tiles = 100
    prev_percentile = min(x_gene)
    for i in range(n_tiles):
        q = (i+1) / float(n_tiles) * 100.
        percentile = np.percentile(x_gene, q)
        idx = np.logical_and(prev_percentile <= x_gene,
                             x_gene <= percentile)
        colors[idx] = i
        prev_percentile = percentile

    colors = colors.flatten()

    if new_fig:
        plt.figure()
        plt.title(viz_prefix)
    plt.scatter(coords[:, 0], coords[:, 1],
                c=colors, cmap=cm.get_cmap('Reds'), s=size)
    plt.savefig(image_fname, dpi=500) 
Example 28
Project: c3dpo_nrsfm   Author: facebookresearch   File: vis_utils.py    License: MIT License 5 votes vote down vote up
def visdom_plot_pointclouds(viz, pcl, visdom_env, title,
                            plot_legend=True, markersize=2,
                            nmax=5000, sticks=None, win=None):

    if sticks is not None:
        pcl = {k: extend_to_3d_skeleton_simple(v, sticks)[0]
               for k, v in pcl.items()}

    legend = list(pcl.keys())

    cmap = 'tab10'
    npcl = len(pcl)
    rgb = (cm.get_cmap(cmap)(np.linspace(0, 1, 10))
           [:, :3]*255.).astype(np.int32).T
    rgb = np.tile(rgb, (1, int(np.ceil(npcl/10))))[:, 0:npcl]

    rgb_cat = {k: np.tile(rgb[:, i:i+1], (1, p.shape[1])) for
               i, (k, p) in enumerate(pcl.items())}

    rgb_cat = np.concatenate(list(rgb_cat.values()), axis=1)
    pcl_cat = np.concatenate(list(pcl.values()), axis=1)

    if pcl_cat.shape[1] > nmax:
        with NumpySeedFix():
            prm = np.random.permutation(
                pcl_cat.shape[1])[0:nmax]
        pcl_cat = pcl_cat[:, prm]
        rgb_cat = rgb_cat[:, prm]

    win = viz.scatter(pcl_cat.T, env=visdom_env,
                      opts={'title': title, 'markersize': markersize,
                            'markercolor': rgb_cat.T}, win=win)
    # legend
    if plot_legend:
        dummy_vals = np.tile(
            np.arange(npcl)[:, None], (1, 2)).astype(np.float32)
        title = "%s_%s" % (title, legend)
        opts = dict(title=title, legend=legend, width=400, height=400)
        viz.line(dummy_vals.T, env=visdom_env, opts=opts)

    return win 
Example 29
Project: Learning2AdaptForStereo   Author: CVLAB-Unibo   File: preprocessing.py    License: Apache License 2.0 5 votes vote down vote up
def colorize_img(value, vmin=None, vmax=None, cmap=None):
    """
    A utility function for TensorFlow that maps a grayscale image to a matplotlib colormap for use with TensorBoard image summaries.
    By default it will normalize the input value to the range 0..1 before mapping to a grayscale colormap.
    Arguments:
      - value: 4D Tensor of shape [batch_size,height, width,1]
      - vmin: the minimum value of the range used for normalization. (Default: value minimum)
      - vmax: the maximum value of the range used for normalization. (Default: value maximum)
      - cmap: a valid cmap named for use with matplotlib's 'get_cmap'.(Default: 'gray')
    
    Returns a 3D tensor of shape [batch_size,height, width,3].
    """

    # normalize
    vmin = tf.reduce_min(value) if vmin is None else vmin
    vmax = tf.reduce_max(value) if vmax is None else vmax
    value = (value - vmin) / (vmax - vmin) # vmin..vmax

    # quantize
    indices = tf.to_int32(tf.round(value[:,:,:,0]*255))

    # gather
    color_map = cm.get_cmap(cmap if cmap is not None else 'gray')
    colors = color_map(np.arange(256))[:,:3]
    colors = tf.constant(colors, dtype=tf.float32)
    value = tf.gather(colors, indices)
    return value

###PER LOSS RIPROIEZIONE### 
Example 30
Project: KittiSeg   Author: MarvinTeichmann   File: seg_utils.py    License: MIT License 5 votes vote down vote up
def make_overlay(image, gt_prob):

    mycm = cm.get_cmap('bwr')

    overimage = mycm(gt_prob, bytes=True)
    output = 0.4*overimage[:,:,0:3] + 0.6*image

    return output