Python matplotlib.cm.gray() Examples

The following are 22 code examples for showing how to use matplotlib.cm.gray(). 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: Deep_Inside_Convolutional_Networks   Author: artvandelay   File: backprop_analysis.py    License: MIT License 6 votes vote down vote up
def vis_square(data, padsize=1, padval=0):
    data -= data.min()
    data /= data.max()
    
    # force the number of filters to be square
    n = int(np.ceil(np.sqrt(data.shape[0])))
    padding = ((0, n ** 2 - data.shape[0]), (0, padsize), (0, padsize)) + ((0, 0),) * (data.ndim - 3)
    data = np.pad(data, padding, mode='constant', constant_values=(padval, padval))
    
    # tile the filters into an image
    data = data.reshape((n, n) + data.shape[1:]).transpose((0, 2, 1, 3) + tuple(range(4, data.ndim + 1)))
    data = data.reshape((n * data.shape[1], n * data.shape[3]) + data.shape[4:])
    
    plt.imshow(data,cmap=cm.gray)



#Perform a forward pass with the data as the input image 
Example 2
Project: neural-network-animation   Author: miloharper   File: test_png.py    License: MIT License 6 votes vote down vote up
def test_pngsuite():
    dirname = os.path.join(
        os.path.dirname(__file__),
        'baseline_images',
        'pngsuite')
    files = glob.glob(os.path.join(dirname, 'basn*.png'))
    files.sort()

    fig = plt.figure(figsize=(len(files), 2))

    for i, fname in enumerate(files):
        data = plt.imread(fname)
        cmap = None  # use default colormap
        if data.ndim == 2:
            # keep grayscale images gray
            cmap = cm.gray
        plt.imshow(data, extent=[i, i + 1, 0, 1], cmap=cmap)

    plt.gca().patch.set_facecolor("#ddffff")
    plt.gca().set_xlim(0, len(files)) 
Example 3
Project: python3_ios   Author: holzschu   File: test_png.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_pngsuite():
    dirname = os.path.join(
        os.path.dirname(__file__),
        'baseline_images',
        'pngsuite')
    files = sorted(glob.iglob(os.path.join(dirname, 'basn*.png')))

    fig = plt.figure(figsize=(len(files), 2))

    for i, fname in enumerate(files):
        data = plt.imread(fname)
        cmap = None  # use default colormap
        if data.ndim == 2:
            # keep grayscale images gray
            cmap = cm.gray
        plt.imshow(data, extent=[i, i + 1, 0, 1], cmap=cmap)

    plt.gca().patch.set_facecolor("#ddffff")
    plt.gca().set_xlim(0, len(files)) 
Example 4
Project: spm1d   Author: 0todd0000   File: _plot.py    License: GNU General Public License v3.0 6 votes vote down vote up
def plot_design(self, factor_labels=None, fontsize=10):
		def scaleColumns(X):
			mn,mx     = np.min(X,axis=0) , np.max(X,axis=0)
			Xs        = (X-mn)/(mx-mn+eps)
			Xs[np.isnan(Xs)] = 1   #if the whole column is a constant
			return Xs
		X             = self.spm.X
		vmin,vmax     = None, None
		if np.all(X==1):
			vmin,vmax = 0, 1
		self.ax.imshow(scaleColumns(X), cmap=colormaps.gray, interpolation='nearest', vmin=vmin, vmax=vmax)
		if factor_labels != None:
			gs        = X.shape
			tx        = [self.ax.text(i, -0.05*gs[0], label)   for i,label in enumerate(factor_labels)]
			pyplot.setp(tx, ha='center', va='bottom', color='k', fontsize=fontsize)
		self.ax.axis('normal')
		self.ax.axis('off') 
Example 5
Project: devito   Author: devitocodes   File: plotting.py    License: MIT License 6 votes vote down vote up
def plot_image(data, vmin=None, vmax=None, colorbar=True, cmap="gray"):
    """
    Plot image data, such as RTM images or FWI gradients.

    Parameters
    ----------
    data : ndarray
        Image data to plot.
    cmap : str
        Choice of colormap. Defaults to gray scale for images as a
        seismic convention.
    """
    plot = plt.imshow(np.transpose(data),
                      vmin=vmin or 0.9 * np.min(data),
                      vmax=vmax or 1.1 * np.max(data),
                      cmap=cmap)

    # Create aligned colorbar on the right
    if colorbar:
        ax = plt.gca()
        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", size="5%", pad=0.05)
        plt.colorbar(plot, cax=cax)
    plt.show() 
Example 6
Project: camera.py   Author: smidm   File: camera_test.py    License: MIT License 6 votes vote down vote up
def calibrate_division_model_test():
    img = rgb2gray(plt.imread('test/kamera2.png'))
    y0 = np.array(img.shape)[::-1][np.newaxis].T / 2.
    z_n = np.linalg.norm(np.array(img.shape) / 2.)
    points = pilab_annotate_load('test/kamera2_lines.xml')
    points_per_line = 5
    num_lines = points.shape[0] / points_per_line
    lines_coords = np.array([points[i * points_per_line:i * points_per_line + points_per_line] for i in xrange(num_lines)])
    c = camera.calibrate_division_model(lines_coords, y0, z_n)

    import matplotlib.cm as cm
    plt.figure()
    plt.imshow(img, cmap=cm.gray)
    for line in xrange(num_lines):
        x = lines_coords[line, :, 0]
        plt.plot(x, lines_coords[line, :, 1], 'g')
        mc = camera.fit_line(lines_coords[line].T)
        plt.plot(x, mc[0] * x + mc[1], 'y')
        xy = c.undistort(lines_coords[line].T)
        plt.plot(xy[0, :], xy[1, :], 'r')
    plt.show()
    plt.close() 
Example 7
Project: coffeegrindsize   Author: jgagneastro   File: test_png.py    License: MIT License 6 votes vote down vote up
def test_pngsuite():
    dirname = os.path.join(
        os.path.dirname(__file__),
        'baseline_images',
        'pngsuite')
    files = sorted(glob.iglob(os.path.join(dirname, 'basn*.png')))

    fig = plt.figure(figsize=(len(files), 2))

    for i, fname in enumerate(files):
        data = plt.imread(fname)
        cmap = None  # use default colormap
        if data.ndim == 2:
            # keep grayscale images gray
            cmap = cm.gray
        plt.imshow(data, extent=[i, i + 1, 0, 1], cmap=cmap)

    plt.gca().patch.set_facecolor("#ddffff")
    plt.gca().set_xlim(0, len(files)) 
Example 8
Project: twitter-stock-recommendation   Author: alvarobartt   File: test_png.py    License: MIT License 6 votes vote down vote up
def test_pngsuite():
    dirname = os.path.join(
        os.path.dirname(__file__),
        'baseline_images',
        'pngsuite')
    files = sorted(glob.iglob(os.path.join(dirname, 'basn*.png')))

    fig = plt.figure(figsize=(len(files), 2))

    for i, fname in enumerate(files):
        data = plt.imread(fname)
        cmap = None  # use default colormap
        if data.ndim == 2:
            # keep grayscale images gray
            cmap = cm.gray
        plt.imshow(data, extent=[i, i + 1, 0, 1], cmap=cmap)

    plt.gca().patch.set_facecolor("#ddffff")
    plt.gca().set_xlim(0, len(files)) 
Example 9
Project: LSDMappingTools   Author: LSDtopotools   File: raster_plotter_2d_ascii_chanfile_version.py    License: MIT License 5 votes vote down vote up
def cumulative_rainfall_catchment(hillshade_file, radar_data_totals):
    """
    Plots the catchment hillshade and overlays the total rainfalls accumulated
    during the model run.
    """
    label_size = 20
    #title_size = 30
    axis_size = 28

    import matplotlib.pyplot as pp
    import numpy as np
    import matplotlib.colors as colors
    import matplotlib.cm as cmx
    from matplotlib import rcParams
    import matplotlib.lines as mpllines
    
    #get data
    #hillshade, hillshade_header = read_flt(hillshade_file)
    
    hillshade, hillshade_header = read_ascii_raster(hillshade_file)
    rainfall_totals = np.loadtxt(radar_data_totals)
    
    #ignore nodata values    
    hillshade = np.ma.masked_where(hillshade == -9999, hillshade)    
    
    #fonts
    rcParams['font.family'] = 'sans-serif'
    rcParams['font.sans-serif'] = ['Liberation Sans']
    rcParams['font.size'] = label_size      
    
    fig = pp.figure(1, facecolor='white',figsize=(10,7.5))
    ax = fig.add_subplot(1,1,1)
    
    plt.imshow(hillshade, vmin=0, vmax=255, cmap=cmx.gray)
    plt.imshow(rainfall_totals, interpolation="none", alpha=0.2) 
Example 10
Project: LSDMappingTools   Author: LSDtopotools   File: LSDMappingTools.py    License: MIT License 5 votes vote down vote up
def simple_density_plot_asc(rfname):

  import numpy as np, matplotlib.pyplot as plt
  from matplotlib import rcParams
  import matplotlib.colors as colors
  import matplotlib.cm as cmx

  label_size = 20
  #title_size = 30
  axis_size = 28

  # Set up fonts for plots
  rcParams['font.family'] = 'sans-serif'
  rcParams['font.sans-serif'] = ['Liberation Sans']
  rcParams['font.size'] = label_size 

  # get the data
  raster,header = read_ascii_raster(rfname)

  # now get the extent
  extent_raster = get_raster_extent_asc(header)

  #print extent_raster

  # make a figure, sized for a ppt slide
  fig = plt.figure(1, facecolor='white',figsize=(10,7.5))
  ax1 =  fig.add_subplot(1,1,1)
  im = ax1.imshow(raster, cmap='gray', extent = extent_raster)
  ax1.set_xlabel("Easting (m)")
  ax1.set_ylabel("Northing (m)")
  im.set_clim(0, np.max(raster))
  cbar = fig.colorbar(im, orientation='horizontal')
  cbar.set_label("Elevation in meters")  

  plt.show() 
Example 11
Project: Computable   Author: ktraunmueller   File: pyplot.py    License: MIT License 5 votes vote down vote up
def gray():
    '''
    set the default colormap to gray and apply to current image if any.
    See help(colormaps) for more information
    '''
    rc('image', cmap='gray')
    im = gci()

    if im is not None:
        im.set_cmap(cm.gray)
    draw_if_interactive()


# This function was autogenerated by boilerplate.py.  Do not edit as
# changes will be lost 
Example 12
Project: matplotlib-4-abaqus   Author: Solid-Mechanics   File: pyplot.py    License: MIT License 5 votes vote down vote up
def gray():
    '''
    set the default colormap to gray and apply to current image if any.
    See help(colormaps) for more information
    '''
    rc('image', cmap='gray')
    im = gci()

    if im is not None:
        im.set_cmap(cm.gray)
    draw_if_interactive()


# This function was autogenerated by boilerplate.py.  Do not edit as
# changes will be lost 
Example 13
Project: neural-network-animation   Author: miloharper   File: pyplot.py    License: MIT License 5 votes vote down vote up
def gray():
    '''
    set the default colormap to gray and apply to current image if any.
    See help(colormaps) for more information
    '''
    rc('image', cmap='gray')
    im = gci()

    if im is not None:
        im.set_cmap(cm.gray)
    draw_if_interactive()


# This function was autogenerated by boilerplate.py.  Do not edit as
# changes will be lost 
Example 14
Project: dfc2019   Author: pubgeo   File: epipolar.py    License: MIT License 5 votes vote down vote up
def show_rectified_images(rimg1, rimg2):
    ax = pl.subplot(121)
    pl.imshow(rimg1, cmap=cm.gray)

    # Hack to get the lines span on the left image
    # http://stackoverflow.com/questions/6146290/plotting-a-line-over-several-graphs
    for i in range(1, rimg1.shape[0], int(rimg1.shape[0]/20)):
        pl.axhline(y=i, color='g', xmin=0, xmax=1.2, clip_on=False);

    pl.subplot(122)
    pl.imshow(rimg2, cmap=cm.gray)
    for i in range(1, rimg1.shape[0], int(rimg1.shape[0]/20)):
        pl.axhline(y=i, color='g'); 
Example 15
Project: devito   Author: devitocodes   File: plotting.py    License: MIT License 5 votes vote down vote up
def plot_shotrecord(rec, model, t0, tn, colorbar=True):
    """
    Plot a shot record (receiver values over time).

    Parameters
    ----------
    rec :
        Receiver data with shape (time, points).
    model : Model
        object that holds the velocity model.
    t0 : int
        Start of time dimension to plot.
    tn : int
        End of time dimension to plot.
    """
    scale = np.max(rec) / 10.
    extent = [model.origin[0], model.origin[0] + 1e-3*model.domain_size[0],
              1e-3*tn, t0]

    plot = plt.imshow(rec, vmin=-scale, vmax=scale, cmap=cm.gray, extent=extent)
    plt.xlabel('X position (km)')
    plt.ylabel('Time (s)')

    # Create aligned colorbar on the right
    if colorbar:
        ax = plt.gca()
        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", size="5%", pad=0.05)
        plt.colorbar(plot, cax=cax)
    plt.show() 
Example 16
Project: LSDMappingTools   Author: LSDtopotools   File: raster_plotter_2d_ascii_chanfile_version.py    License: MIT License 4 votes vote down vote up
def plot_ChiMValues_hillshade(hillshade_file, m_value_file):
    
    """
    Pass in a hillshade and chiMvalues flt file and plot the results over
    a greyscale hillshade
    """

    import matplotlib.pyplot as pp
    import matplotlib.cm as cm
    from matplotlib import rcParams
    import numpy as np
    
    #get data
    hillshade, hillshade_header = read_flt(hillshade_file)
    m_values, m_values_header = read_flt(m_value_file)
    
    #ignore nodata values    
    hillshade = np.ma.masked_where(hillshade == -9999, hillshade)    
    m_values = np.ma.masked_where(m_values == -9999, m_values)
    
    #fonts
    rcParams['font.family'] = 'sans-serif'
    rcParams['font.sans-serif'] = ['Liberation Sans']
    rcParams['font.size'] = 12  

    fig, ax = pp.subplots()
    
    #plot the arrays
    ax.imshow(hillshade, vmin=0, vmax=255, cmap=cm.gray)
    data = ax.imshow(m_values, interpolation='none', vmin=m_values.min(), vmax=m_values.max(), cmap=cm.jet)
    
    xlocs, xlabels = pp.xticks()
    ylocs, ylabels = pp.yticks()
   
    new_x_labels = np.linspace(hillshade_header[2],hillshade_header[2]+(hillshade_header[1]*hillshade_header[4]), len(xlocs))
    new_y_labels = np.linspace(hillshade_header[3],hillshade_header[3]+(hillshade_header[0]*hillshade_header[4]), len(ylocs))        
    
    new_x_labels = [str(x).split('.')[0] for x in new_x_labels] #get rid of decimal places in axis ticks
    new_y_labels = [str(y).split('.')[0] for y in new_y_labels][::-1] #invert y axis
    pp.xticks(xlocs[1:-1], new_x_labels[1:-1], rotation=30)  #[1:-1] skips ticks where we have no data
    pp.yticks(ylocs[1:-1], new_y_labels[1:-1])    
    
    fig.colorbar(data).set_label('M Values')
    pp.xlabel('Easting (m)')
    pp.ylabel('Northing (m)')
    
    pp.show() 
Example 17
Project: Computable   Author: ktraunmueller   File: pyplot.py    License: MIT License 4 votes vote down vote up
def colors():
    """
    This is a do-nothing function to provide you with help on how
    matplotlib handles colors.

    Commands which take color arguments can use several formats to
    specify the colors.  For the basic built-in colors, you can use a
    single letter

      =====   =======
      Alias   Color
      =====   =======
      'b'     blue
      'g'     green
      'r'     red
      'c'     cyan
      'm'     magenta
      'y'     yellow
      'k'     black
      'w'     white
      =====   =======

    For a greater range of colors, you have two options.  You can
    specify the color using an html hex string, as in::

      color = '#eeefff'

    or you can pass an R,G,B tuple, where each of R,G,B are in the
    range [0,1].

    You can also use any legal html name for a color, for example::

      color = 'red'
      color = 'burlywood'
      color = 'chartreuse'

    The example below creates a subplot with a dark
    slate gray background::

       subplot(111, axisbg=(0.1843, 0.3098, 0.3098))

    Here is an example that creates a pale turquoise title::

      title('Is this the best color?', color='#afeeee')

    """
    pass 
Example 18
Project: matplotlib-4-abaqus   Author: Solid-Mechanics   File: pyplot.py    License: MIT License 4 votes vote down vote up
def colors():
    """
    This is a do-nothing function to provide you with help on how
    matplotlib handles colors.

    Commands which take color arguments can use several formats to
    specify the colors.  For the basic built-in colors, you can use a
    single letter

      =====   =======
      Alias   Color
      =====   =======
      'b'     blue
      'g'     green
      'r'     red
      'c'     cyan
      'm'     magenta
      'y'     yellow
      'k'     black
      'w'     white
      =====   =======

    For a greater range of colors, you have two options.  You can
    specify the color using an html hex string, as in::

      color = '#eeefff'

    or you can pass an R,G,B tuple, where each of R,G,B are in the
    range [0,1].

    You can also use any legal html name for a color, for example::

      color = 'red'
      color = 'burlywood'
      color = 'chartreuse'

    The example below creates a subplot with a dark
    slate gray background::

       subplot(111, axisbg=(0.1843, 0.3098, 0.3098))

    Here is an example that creates a pale turquoise title::

      title('Is this the best color?', color='#afeeee')

    """
    pass 
Example 19
Project: neural-network-animation   Author: miloharper   File: pyplot.py    License: MIT License 4 votes vote down vote up
def colors():
    """
    This is a do-nothing function to provide you with help on how
    matplotlib handles colors.

    Commands which take color arguments can use several formats to
    specify the colors.  For the basic built-in colors, you can use a
    single letter

      =====   =======
      Alias   Color
      =====   =======
      'b'     blue
      'g'     green
      'r'     red
      'c'     cyan
      'm'     magenta
      'y'     yellow
      'k'     black
      'w'     white
      =====   =======

    For a greater range of colors, you have two options.  You can
    specify the color using an html hex string, as in::

      color = '#eeefff'

    or you can pass an R,G,B tuple, where each of R,G,B are in the
    range [0,1].

    You can also use any legal html name for a color, for example::

      color = 'red'
      color = 'burlywood'
      color = 'chartreuse'

    The example below creates a subplot with a dark
    slate gray background::

       subplot(111, axisbg=(0.1843, 0.3098, 0.3098))

    Here is an example that creates a pale turquoise title::

      title('Is this the best color?', color='#afeeee')

    """
    pass 
Example 20
Project: python3_ios   Author: holzschu   File: demo_agg_filter.py    License: BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def filtered_text(ax):
    # mostly copied from contour_demo.py

    # prepare image
    delta = 0.025
    x = np.arange(-3.0, 3.0, delta)
    y = np.arange(-2.0, 2.0, delta)
    X, Y = np.meshgrid(x, y)
    Z1 = np.exp(-X**2 - Y**2)
    Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
    Z = (Z1 - Z2) * 2

    # draw
    im = ax.imshow(Z, interpolation='bilinear', origin='lower',
                   cmap=cm.gray, extent=(-3, 3, -2, 2))
    levels = np.arange(-1.2, 1.6, 0.2)
    CS = ax.contour(Z, levels,
                    origin='lower',
                    linewidths=2,
                    extent=(-3, 3, -2, 2))

    ax.set_aspect("auto")

    # contour label
    cl = ax.clabel(CS, levels[1::2],  # label every second level
                   inline=1,
                   fmt='%1.1f',
                   fontsize=11)

    # change clable color to black
    from matplotlib.patheffects import Normal
    for t in cl:
        t.set_color("k")
        # to force TextPath (i.e., same font in all backends)
        t.set_path_effects([Normal()])

    # Add white glows to improve visibility of labels.
    white_glows = FilteredArtistList(cl, GrowFilter(3))
    ax.add_artist(white_glows)
    white_glows.set_zorder(cl[0].get_zorder() - 0.1)

    ax.xaxis.set_visible(False)
    ax.yaxis.set_visible(False) 
Example 21
Project: lie_learn   Author: AMLab-Amsterdam   File: S2.py    License: MIT License 4 votes vote down vote up
def plot_sphere_func2(f, grid='Clenshaw-Curtis', beta=None, alpha=None, colormap='jet', fignum=0,  normalize=True):
    # TODO: update this  function now that we have changed the order of axes in f
    import matplotlib.pyplot as plt
    from matplotlib import cm, colors
    from mpl_toolkits.mplot3d import Axes3D
    import numpy as np
    from scipy.special import sph_harm

    if normalize:
        f = (f - np.min(f)) / (np.max(f) - np.min(f))

    if grid == 'Driscoll-Healy':
        b = f.shape[0] // 2
    elif grid == 'Clenshaw-Curtis':
        b = (f.shape[0] - 2) // 2
    elif grid == 'SOFT':
        b = f.shape[0] // 2
    elif grid == 'Gauss-Legendre':
        b = (f.shape[0] - 2) // 2

    if beta is None or alpha is None:
        beta, alpha = meshgrid(b=b, grid_type=grid)

    alpha = np.r_[alpha, alpha[0, :][None, :]]
    beta = np.r_[beta, beta[0, :][None, :]]
    f = np.r_[f, f[0, :][None, :]]

    x = np.sin(beta) * np.cos(alpha)
    y = np.sin(beta) * np.sin(alpha)
    z = np.cos(beta)

    # m, l = 2, 3
    # Calculate the spherical harmonic Y(l,m) and normalize to [0,1]
    # fcolors = sph_harm(m, l, beta, alpha).real
    # fmax, fmin = fcolors.max(), fcolors.min()
    # fcolors = (fcolors - fmin) / (fmax - fmin)
    print(x.shape, f.shape)

    if f.ndim == 2:
        f = cm.gray(f)
        print('2')

    # Set the aspect ratio to 1 so our sphere looks spherical
    fig = plt.figure(figsize=plt.figaspect(1.))
    ax = fig.add_subplot(111, projection='3d')
    ax.plot_surface(x, y, z, rstride=1, cstride=1, facecolors=f ) # cm.gray(f))
    # Turn off the axis planes
    ax.set_axis_off()
    plt.show() 
Example 22
Project: pyret   Author: baccuslab   File: visualizations.py    License: MIT License 4 votes vote down vote up
def play_rates(rates, patches, num_levels=255, time=None,
        repeat=True, frametime=100):
    """
    Plays a movie representation of the firing rate of a list of cells, by
    coloring a list of patches with a color proportional to the firing rate. This
    is useful, for example, in conjunction with ``plot_cells``, to color the
    ellipses fitted to a set of receptive fields proportional to the firing rate.

    Parameters
    ----------
    rates : array_like
        An ``(N, T)`` matrix of firing rates. ``N`` is the number of cells, and
        ``T`` gives the firing rate at a each time point.

    patches : list
        A list of ``N`` matplotlib patch elements. The facecolor of these patches is
        altered according to the rates values.

    Returns
    -------
    anim : matplotlib.animation.Animation
        The object representing the full animation.
    """
    # Validate input
    if rates.ndim == 1:
        rates = rates.reshape(1, -1)
    if isinstance(patches, Ellipse):
        patches = [patches]
    N, T = rates.shape

    # Approximate necessary colormap
    colors = cm.gray(np.arange(num_levels))
    rscale = np.round((num_levels - 1) * (rates - rates.min()) /
                      (rates.max() - rates.min())).astype('int').reshape(N, T)

    # set up
    fig = plt.gcf()
    ax = plt.gca()
    if time is None:
        time = np.arange(T)

    # Animation function (called sequentially)
    def animate(t):
        for i in range(N):
            patches[i].set_facecolor(colors[rscale[i, t]])
        ax.set_title('Time: %0.2f seconds' % (time[t]), fontsize=20)

    # Call the animator
    anim = animation.FuncAnimation(fig, animate,
                                   np.arange(T), interval=frametime, repeat=repeat)
    return anim