Python matplotlib.cm 模块,gray() 实例源码

我们从Python开源项目中,提取了以下9个代码示例,用于说明如何使用matplotlib.cm.gray()

项目:devito    作者:opesci    | 项目源码 | 文件源码
def plot_shotrecord(rec, model, t0, tn, colorbar=True):
    """
    Plot a shot record (receiver values over time).

    :param rec: Receiver data with shape (time, points)
    :param model: :class:`Model` object that holds the velocity model.
    :param t0: Start of time dimension to plot
    :param tn: 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()
项目:devito    作者:opesci    | 项目源码 | 文件源码
def plot_image(data, vmin=None, vmax=None, colorbar=True, cmap="gray"):
    """
    Plot image data, such as RTM images or FWI gradients.

    :param data: Image data to plot
    :param cmap: Choice of colormap, default is 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()
项目:pyOpenAireTextClassifier    作者:tyiannak    | 项目源码 | 文件源码
def drawGraphFromSM2(SM, names, outFile, Cut):
    graph = pydot.Dot(graph_type='graph')

    # THRESHOLD SM:
    nonZeroMean = np.mean(SM[SM.nonzero()])
    if Cut:
        T = 5.0 * nonZeroMean
    else:
        T = 0.0;

    for i in range(SM.shape[0]):
        for j in range(SM.shape[0]):
            if SM[i,j] <= T:
                SM[i,j] = 0.0
            else:
                SM[i,j] = 1.0

    numOfConnections = sum(SM, axis = 0)
    #fig = plt.figure(1)
    #plot1 = plt.imshow(SM, origin='upper', cmap=cm.gray, interpolation='nearest')
    #plt.show()

    numOfConnections = 9*numOfConnections / max(numOfConnections)

    for i,f in enumerate(names):    
        if sum(SM[i,:])>0:
            fillColorCurrent = "{0:d}".format(int(ceil(numOfConnections[i])))
            # NOTE: SEE http://www.graphviz.org/doc/info/colors.html for color schemes
            node = pydot.Node(f, style="filled", fontsize="8", shape="egg", fillcolor=fillColorCurrent, colorscheme = "reds9")
            graph.add_node(node)

    for i in range(len(names)):
        for j in range(len(names)):
            if i<j:
                if SM[i][j] > 0:
                    #gr.add_edge((names[i], names[j]))              
                    edge = pydot.Edge(names[i], names[j])   
                    graph.add_edge(edge)
    graph.write_png(outFile)
项目:pyOpenAireTextClassifier    作者:tyiannak    | 项目源码 | 文件源码
def drawGraphFromSM(SM, names, outFile):
    fig = plt.figure(1)
    plot1 = plt.imshow(SM, origin='upper', cmap=cm.gray, interpolation='nearest')
    plt.show()

    gr = graph()

    namesNew = []
    for i,f in enumerate(names):    
        if sum(SM[i,:])>0:
            gr.add_nodes([f])
            namesNew.append(f)

    Max = SM.max()
    Mean = mean(SM)

    Threshold = Mean * 1.5
    for i in range(len(names)):
        for j in range(len(names)):
            if i<j:
                if SM[i][j] > 0:
                    gr.add_edge((names[i], names[j]))
    # Draw as PNG
    dot = write(gr)
    gvv = gv.readstring(dot)
    gv.layout(gvv,'dot')
    gv.render(gvv,'png', outFile)
项目:DeepCellSeg    作者:arbellea    | 项目源码 | 文件源码
def plot_segmentation(I,GT,Seg, fig=None):

    I = np.squeeze(I)
    GT = np.squeeze(GT)
    Seg = np.squeeze(Seg)

    GTC = np.logical_and(GT, np.logical_not(ndimage.binary_erosion(GT)))
    SegC = np.logical_and(Seg, np.logical_not(ndimage.binary_erosion(Seg)))

    plt.figure(fig)
    maskedGT = np.ma.masked_where(GTC == 0, GTC)
    maskedSeg = np.ma.masked_where(SegC == 0, SegC)
    plt.imshow(I, cmap=cm.gray)
    plt.imshow(maskedGT, cmap=cm.jet, interpolation='none')
    plt.imshow(maskedSeg*100, cmap=cm.hsv, interpolation='none')
项目:pymake    作者:dtrckd    | 项目源码 | 文件源码
def scaledimage(W, pixwidth=1, ax=None, grayscale=True):
    """
    Do intensity plot, similar to MATLAB imagesc()

    W = intensity matrix to visualize
    pixwidth = size of each W element
    ax = matplotlib Axes to draw on
    grayscale = use grayscale color map

    Rely on caller to .show()
    """

    # N = rows, M = column
    (N, M) = W.shape
    # Need to create a new Axes?
    if(ax == None):
        ax = plt.figure().gca()
    # extents = Left Right Bottom Top
    exts = (0, pixwidth * M, 0, pixwidth * N)
    if(grayscale):
        ax.imshow(W,
                  interpolation='nearest',
                  cmap=CM.gray,
                  extent=exts)
    else:
        ax.imshow(W,
                  interpolation='nearest',
                  extent=exts)

    ax.xaxis.set_major_locator(MT.NullLocator())
    ax.yaxis.set_major_locator(MT.NullLocator())
    return ax
项目:ip-avsr    作者:lzuwei    | 项目源码 | 文件源码
def show_image(data, shape, order='f', cmap=cm.gray):
    """
    display an image from a 1d vector
    :param data: 1d vector containing image information
    :param shape: actual image dimensions
    :param order: 'c' or 'f'
    :param cmap: colour map, defaults to grayscale
    :return:
    """
    img = data.reshape(shape, order=order)
    plt.imshow(img, cmap=cmap)
    plt.show()
项目:pynufft    作者:jyhmiinlin    | 项目源码 | 文件源码
def example_3D():


    import pkg_resources

    DATA_PATH = pkg_resources.resource_filename('pynufft', './src/data/')   

    image = numpy.load(DATA_PATH +'phantom_3D_128_128_128.npz')['arr_0'][0::2, 0::2, 0::2]


    pyplot.imshow(numpy.abs(image[:,:,32]), label='original signal',cmap=gray)
    pyplot.show()


    Nd = (64,64,64) # time grid, tuple
    Kd = (64,64,64) # frequency grid, tuple
    Jd = (1,1,1) # interpolator 
#     om=       numpy.load(DATA_PATH+'om3D.npz')['arr_0']
    om = numpy.random.randn(15120,3)
    print(om.shape)
    from ..pynufft import NUFFT_cpu, NUFFT_hsa
    NufftObj = NUFFT_cpu()


    NufftObj.plan(om, Nd, Kd, Jd)

    kspace =NufftObj.forward(image)

    restore_image = NufftObj.solve(kspace,'cg', maxiter=200)

    restore_image1 = NufftObj.solve(kspace,'L1TVLAD', maxiter=200,rho=0.1)
# 
    restore_image2 = NufftObj.solve(kspace,'L1TVOLS', maxiter=200,rho=0.1)
    pyplot.subplot(2,2,1)
    pyplot.imshow(numpy.abs(image[:,:,32]), label='original signal',cmap=gray)
    pyplot.title('original')    
    pyplot.subplot(2,2,2)
    pyplot.imshow(numpy.abs(restore_image1[:,:,32]), label='L1TVLAD',cmap=gray)
    pyplot.title('L1TVLAD')

    pyplot.subplot(2,2,3)
    pyplot.imshow(numpy.abs(restore_image2[:,:,32]), label='L1TVOLS',cmap=gray)
    pyplot.title('L1TVOLS')



    pyplot.subplot(2,2,4)
    pyplot.imshow(numpy.abs(restore_image[:,:,32]), label='CG',cmap=gray)
    pyplot.title('CG')
#     pyplot.legend([im1, im im4])


    pyplot.show()
项目:Multi-views-fusion    作者:luogongning    | 项目源码 | 文件源码
def crop_resize(img,space):
    """
    Crop center and resize.

    :param img: image to be cropped and resized.
    """
    ws=float(space[0])
    hs=float(space[1])
    wsextend= ws/1.4
    hsextend=hs/1.4
    wsint= int(img.shape[0]*wsextend)
    if wsint%2!=0:
        wsint+=1
    hsint=int(img.shape[1]*hsextend)
    if hsint%2!=0:
        hsint+=1
    #if img.shape[0] < img.shape[1]:
        #img = img.T
    # we crop image from center
    image_shape=(wsint,hsint)
    img = imresize(img, image_shape)
    #plt.imshow(img,cmap=cm.gray)
    #short_edge = min(img.shape[:2])
    yyy=img.shape[0]
    xxx=img.shape[1]
    yy = int((img.shape[0] - cropsize) / 2)
    xx = int((img.shape[1] - cropsize) / 2)
    if (yy<=0) and (xx<=0) :
        crop_img=np.zeros((cropsize, cropsize), dtype=np.float32)
        for i in range(-yy,-yy+yyy):
            for j in range(-xx,-xx+xxx):
                crop_img[i][j]=img[i+yy][j+xx]
        img=crop_img
    elif (yy<=0) and (xx>=0) :
        crop_img=np.zeros((cropsize, cropsize), dtype=np.float32)
        for i in range(-yy,-yy+yyy):
            for j in range(0,cropsize):
                crop_img[i][j]=img[i+yy][j+xx]
        img=crop_img
    elif (yy>=0) and (xx<=0) :
        crop_img=np.zeros((cropsize, cropsize), dtype=np.float32)
        for i in range(0,cropsize):
            for j in range(-xx,-xx+xxx):
                crop_img[i][j]=img[i+yy][j+xx]
        img=crop_img
    else:
        crop_img = img[yy: yy + cropsize, xx: xx + cropsize]
        img = crop_img
    img = imresize(img, img_shape)
    return img