当前位置: 首页>>代码示例>>Python>>正文


Python pylab.gray函数代码示例

本文整理汇总了Python中pylab.gray函数的典型用法代码示例。如果您正苦于以下问题:Python gray函数的具体用法?Python gray怎么用?Python gray使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了gray函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: demo_histeq

def demo_histeq():
    """
    Gray histogram equalization, make every gray value have same distribution.
    This process could imporve contrast of image.
    """
    im = np.array(Image.open('./computer_vision/scenery.jpg').convert('L'))
    imhist, bins = np.histogram(im.flatten(), bins = 256, normed = True)
    cdf = imhist.cumsum()
    """Normalization"""
    cdf = 255 * cdf / cdf[-1]
    im_n = np.interp(im.flatten(),bins[:-1], cdf)
    """
    Image of equalization.
    I don't know why reshape() function can't modify shape attribute, 
    it just change the arrangement of output if you print it out.
    I've tried when you create a array with reshape(), it works.
    """
    #im_n.reshape(im.shape)
    im_n.shape = im.shape
    
    pl.figure('Histogram equalization')
    pl.subplot(1,2,1)
    pl.gray()
    pl.imshow(im)
    pl.title('Orignal gray image')
    pl.subplot(1,2,2)
    pl.gray()
    pl.imshow(im_n)
    pl.title('equalized image')
    pl.show()
开发者ID:T800GHB,项目名称:Python_Basic,代码行数:30,代码来源:basic_process.py

示例2: explore_data

def explore_data(data, images, target):

	# try to determine the type of data...
	print "data_type belonging to key data:"
	try: 
		print np.dtype(data)
	except TypeError as err:
		print err
	
	print "It has dimension", np.shape(data)

	# plot a 3
	
	# get indices of all threes in target
	threes = np.where(target == 3)
	#assert threes is not empty
	assert(len(threes) > 0)
	# choose the first 3
	three_indx = threes[0]
	# get the image
	img = images[three_indx][0]

	#plot it
	plot.figure()
	plot.gray()
	plot.imshow(img, interpolation = "nearest")
	plot.show()
	plot.close()
开发者ID:EmCeeEs,项目名称:machine_learning,代码行数:28,代码来源:ex1.py

示例3: display_head

def display_head(set_x, set_y, n = 5):
    '''
    show some figures based on gray image matrixs
    
    @type set_x: TensorSharedVariable, 
    @param set_x: gray level value matrix of the
    
    @type set_y: TensorVariable, 
    @param set_y: label of the figures    
    
    @type n: int, 
    @param n: numbers of figure to be display, less than 10, default 5
    '''
    import pylab
    
    if n > 10: n = 10
    img_x = set_x.get_value()[0:n].reshape(n, 28, 28)
    img_y = set_y.eval()[0:n]
    
    for i in range(n): 
        pylab.subplot(1, n, i+1); 
        pylab.axis('off'); 
        pylab.title(' %d' % img_y[i])
        pylab.gray()
        pylab.imshow(img_x[i])
开发者ID:LiuYouliang,项目名称:Practice-of-Machine-Learning,代码行数:25,代码来源:MLP.py

示例4: compare_keypoints

def compare_keypoints(im1, im2, pos1, pos2, filename = None, separation = 0) :
    """ Show two images next to each other with the keypoints marked
    """

    # Construct unified image
    im3 = append_images(im1,im2, separation)

    # Find the offset and add it
    offset = im1.shape[1]
    pos2_o = [(x+offset + separation,y) for (x,y) in pos2]

    # Create figure
    fig = pylab.figure(frameon=False, figsize=(12.0, 8.0))
    #ax = pylab.Axes(fig, [0., 0., 1., 1.])

    # Show images
    pylab.gray()
    pylab.imshow(im3)
    pylab.plot([x for x,y in pos1], [y for x,y in pos1], marker='o', color = '#00aaff', lw=0)
    pylab.plot([x for x,y in pos2_o], [y for x,y in pos2_o], marker='o', color = '#00aaff', lw=0)
    pylab.axis('off')

    pylab.xlim(0,im3.shape[1])
    pylab.ylim(im3.shape[0],0)

    if filename != None :
        fig.savefig(filename, bbox_inches='tight', dpi=300)
开发者ID:arnfred,项目名称:Fast-Match,代码行数:27,代码来源:figures.py

示例5: updateColorTable

    def updateColorTable(self, cItem):
        print "now viz!"+str(cItem.row())+","+str(cItem.column())

        row = cItem.row()
        col = cItem.column()

        pl.clf()
        #pl.ion()
        x = pl.arange(self.dataDimen+1)
        y = pl.arange(self.dataDimen+1)
        X, Y = pl.meshgrid(x, y)
        pl.subplot(1,2,1)
        pl.pcolor(X, Y, self.mWx[row*self.dataMaxRange+col])
        pl.gca().set_aspect('equal')
        pl.colorbar()
        pl.gray()
        pl.title("user 1")

        pl.subplot(1,2,2)
        pl.pcolor(X, Y, self.mWy[row*self.dataMaxRange+col])
        pl.gca().set_aspect('equal')
        pl.colorbar()
        pl.gray()
        pl.title("user 2")
        #pl.tight_layout()

        pl.draw()
        #pl.show()
        pl.show(block=False) 
开发者ID:cvpapero,项目名称:rqt_cca,代码行数:29,代码来源:cca_interface2.py

示例6: apply_conv

def apply_conv(name):
    import pylab
    from PIL import Image

    # open random image of dimensions 639x516
    img = Image.open(open(name))

    # capture image height and width
    width,height = img.size

    # dimensions are (height, width, channel)
    img = numpy.asarray(img, dtype='float64') / 256.

    # put image in 4D tensor of shape (1, 3, height, width)
    img_ = img.transpose(2, 0, 1).reshape(1, 3, height, width)
    filtered_img = f(img_)

    # plot original image and first and second components of output
    pylab.subplot(1, 3, 1); pylab.axis('off'); pylab.imshow(img)
    pylab.gray();
    # recall that the convOp output (filtered image) is actually a "minibatch",
    # of size 1 here, so we take index 0 in the first dimension:
    pylab.subplot(1, 3, 2); pylab.axis('off'); pylab.imshow(filtered_img[0, 0, :, :])
    pylab.subplot(1, 3, 3); pylab.axis('off'); pylab.imshow(filtered_img[0, 1, :, :])
    pylab.show()
开发者ID:rsumana,项目名称:UserProfiling,代码行数:25,代码来源:conv.py

示例7: main

def main():
    """Compute the SSIM index on two input images specified on the cmd line."""
    import pylab
    argv = sys.argv
    if len(argv) != 3:
        print('usage: python -m sp.ssim image1.tif image2.tif', file=sys.stderr)
        sys.exit(2)

    try:
        from PIL import Image
        img1 = numpy.asarray(Image.open(argv[1]))
        img2 = numpy.asarray(Image.open(argv[2]))
    except Exception as e:
        e = 'Cannot load images' + str(e)
        print(e, file=sys.stderr)

    ssim_map = ssim(img1, img2)
    ms_ssim = msssim(img1, img2)

    pylab.figure()
    pylab.subplot(131)
    pylab.title('Image1')
    pylab.imshow(img1, interpolation='nearest', cmap=pylab.gray())
    pylab.subplot(132)
    pylab.title('Image2')
    pylab.imshow(img2, interpolation='nearest', cmap=pylab.gray())
    pylab.subplot(133)
    pylab.title('SSIM Map\n SSIM: %f\n MSSSIM: %f' % (ssim_map.mean(), ms_ssim))
    pylab.imshow(ssim_map, interpolation='nearest', cmap=pylab.gray())
    pylab.show()
    
    return 0
开发者ID:incunabulum,项目名称:signal-processing,代码行数:32,代码来源:ssim.py

示例8: test_rot180

def test_rot180():
    import cudamat
    import numpy as np
    num_images = 100
    img_size = 50
    img_tot_size = 50*50


    inputs = np.random.randn(num_images, img_tot_size)
    inputs[1:] = (np.random.rand(*inputs[1:].shape)<0.5)
    inputs[0] = (np.random.rand(*inputs[1].shape)<0.005)

    targets = np.random.randn(num_images, img_tot_size)

    cu_inputs = cudamat.CUDAMatrix(inputs.T)
    cu_targets = cudamat.CUDAMatrix(targets.T)

    cudamat._cudamat.rot180(cu_inputs.p_mat, cu_targets.p_mat, 0)

    cua_targets = cu_targets.asarray().T

    targets = np.array([x[::-1,::-1]
                        for x in inputs.reshape(num_images, img_size, img_size)]).reshape(num_images, img_tot_size)

    print abs(targets - cua_targets).max()

    from pylab import imshow, subplot, gray
    gray()
    subplot(221)
    imshow(inputs[0].reshape(img_size, img_size), interpolation='nearest')
    subplot(222)
    imshow(targets[0].reshape(img_size, img_size), interpolation='nearest')

    subplot(223)
    imshow(cua_targets[0].reshape(img_size, img_size), interpolation='nearest')
开发者ID:barapa,项目名称:HF-RNN,代码行数:35,代码来源:test_conv.py

示例9: test_copyOutOf

def test_copyOutOf():
    import cudamat
    import numpy as np
    num_images = 100
    img_size = 50
    target_size = 72
    img_tot_size = img_size**2
    target_tot_size = target_size**2

    targets = np.random.randn(target_tot_size, num_images)<-2
    inputs = np.zeros((img_tot_size, num_images))

    cu_inputs = cudamat.CUDAMatrix(inputs)
    cu_targets = cudamat.CUDAMatrix(targets)

    assert (target_size - img_size) % 2 == 0
    padding = (target_size - img_size)/2
    cudamat._cudamat.copy_out_of_center(cu_targets.p_mat, cu_inputs.p_mat, padding, 0)

    cua_inputs = cu_inputs.asarray()

    #print abs(targets - cua_targets).max()

    from pylab import imshow, subplot, gray
    gray()

    #subplot(221)
    #imshow(inputs[0].reshape(img_size, img_size), interpolation='nearest')
    subplot(222)
    imshow(targets[:,1].reshape(target_size, target_size), interpolation='nearest')

    subplot(223)
    imshow(cua_inputs[:,1].reshape(img_size, img_size), interpolation='nearest')
开发者ID:barapa,项目名称:HF-RNN,代码行数:33,代码来源:test_conv.py

示例10: makeTestPair

def makeTestPair(paths, homography, collection, location=".", size=(250,250), scale = 1.0) :
    """ Given a pair of paths to two images and a homography between them,
        this function creates two crops and calculates a new homography.
        input: paths [strings] (paths to images)
               homography [numpy.ndarray] (3 by 3 array homography)
               collection [string] (The name of the testset)
               location [string] (The location (path) of the testset
               size [(int, int)] (The size of an image crop in pixels)
               scale [double] (The scale by which we resize the crops after they've been cropped)
        out:   nothing
    """
    
    # Get width and height
    width, height = size
    
    # Load images in black/white
    images = map(loadImage, paths)
    
    # Crop part of first image and part of second image:
    (top_o, left_o) = (random.randint(0, images[0].shape[0]-height), random.randint(0, images[0].shape[1]-width))
    (top_n, left_n) = (random.randint(0, images[1].shape[0]-height), random.randint(0, images[1].shape[1]-width))
    
    # Get two file names
    c_path = getRandPath("%s/%s/" % (location, collection))
    if not exists(dirname(c_path)) : makedirs(dirname(c_path))
        
    # Make sure we save as gray
    pylab.gray()
    
    im1 = images[0][top_o: top_o + height, left_o: left_o + width]
    im2 = images[1][top_n: top_n + height, left_n: left_n + width]
    im1_scaled = imresize(im1, size=float(scale), interp='bicubic')
    im2_scaled = imresize(im2, size=float(scale), interp='bicubic')
    pylab.imsave(c_path + "_1.jpg", im1_scaled)
    pylab.imsave(c_path + "_2.jpg", im2_scaled)
    
    # Homography for transpose
    T1 = numpy.identity(3)
    T1[0,2] = left_o
    T1[1,2] = top_o
    
    # Homography for transpose back
    T2 = numpy.identity(3)
    T2[0,2] = -1*left_n
    T2[1,2] = -1*top_n
    
    # Homography for scale
    Ts = numpy.identity(3)
    Ts[0,0] = scale
    Ts[1,1] = scale
    
    # Homography for scale back
    Tsinv = numpy.identity(3)
    Tsinv[0,0] = 1.0/scale
    Tsinv[1,1] = 1.0/scale
    
    # Combine homographyies and save
    hom = Ts.dot(T2).dot(homography).dot(T1).dot(Tsinv)
    hom = hom / hom[2,2]
    numpy.savetxt(c_path, hom)
开发者ID:arnfred,项目名称:Mirror-Match,代码行数:60,代码来源:murals.py

示例11: plotSources

def plotSources(im, sources, schema):
    plt.clf()
    plt.imshow(im.getArray(), origin='lower', interpolation='nearest',
               vmin=-100, vmax=500)
    plt.gray()
    shapekey = schema.find('shape.sdss').key
    xykey = schema.find('centroid.sdss').key

    flagkeys = [schema.find(x).key for x in [
        'shape.sdss.flags.maxiter', 'shape.sdss.flags.shift',
        'shape.sdss.flags.unweighted', 'shape.sdss.flags.unweightedbad']]
    flagabbr = ['M','S','U','B']

    for source in sources:
        quad = source.get(shapekey)
        ixx,iyy = quad.getIxx(), quad.getIyy()
        x,y = source.get(xykey)
        sx,sy = sqrt(ixx),sqrt(iyy)
        plt.gca().add_artist(Ellipse([x,y], 2.*sx, 2.*sy, angle=0.,
                                     ec='r', fc='none', lw=2, alpha=0.5))
        fs = ''
        for j,key in enumerate(flagkeys):
            val = source.get(key)
            if val:
                fs += flagabbr[j]
        if len(fs):
            plt.text(x+5, y, fs, ha='left', va='center')
开发者ID:laurenam,项目名称:meas_algorithms,代码行数:27,代码来源:ticket2019.py

示例12: show_weights

def show_weights(layer):        
    while isinstance(layer, lasagne.layers.InputLayer) == False:
        if isinstance(layer, dnn.Conv2DDNNLayer):
            first_conv_layer =  layer
        layer = layer.input_layer
    
    weights = first_conv_layer.get_params()[0].get_value()
    weights_no = weights.shape[0]
    
    display_size = int(math.sqrt(weights_no)) + 1
    
    print 'display_size : %s' % display_size
    
    pylab.gray() 
    for i in range(display_size):
        for j in range(display_size):
            index = i * display_size + j + 1
            
            if index >= weights_no:
                break

            print 'index : %s' % index
    
            one_weight = weights[index][0]
            pylab.subplot(display_size, display_size, index) 
            pylab.axis('off') 
            pylab.imshow(one_weight)
    
    pylab.show()
开发者ID:only4hj,项目名称:fast-rcnn,代码行数:29,代码来源:util.py

示例13: _test

def _test():
    # make a unit circle going counter-clockwise
    radius = 60
    theta = np.linspace(0, 2*np.pi, 10)
    circle_ccw = np.array([radius*np.cos(theta), radius*np.sin(theta)])
    area = ContourArea(circle_ccw)
    assert area > 0
    circle_cw = MakeClockwise(circle_ccw)
    area = ContourArea(circle_cw)
    assert area < 0
    assert (circle_cw == circle_ccw[:,::-1]).all() # it actually got reversed
    p = circle_cw + np.array([[280],[430]])

    plb.ion()
    plb.figure(0)
    plb.gray()
    i = plb.imread('mri2.png')
    i = np.mean(i, axis=2)
    plb.imshow(i)
    global _contour
    _contour, = plb.plot(np.append(p[0,-1], p[0]),np.append(p[1,-1], p[1]))
    plb.draw()
    Snake2D(i, p, iterations=500)
    print 'done'
    plb.ioff()
    plb.savefig('mri-result.png')
    plb.show()
开发者ID:vmonaco,项目名称:balloon-contour,代码行数:27,代码来源:snake2D.py

示例14: main

def main():
    butils = measDeblend.BaselineUtilsF

    foot = buildExample2()

    fbb = foot.getBBox()
    mask1 = afwImg.MaskU(fbb.getWidth(), fbb.getHeight())
    mask1.setXY0(fbb.getMinX(), fbb.getMinY())
    afwDet.setMaskFromFootprint(mask1, foot, 1)

    if plt:
        plt.clf()
        plt.imshow(mask1.getArray(), origin='lower', interpolation='nearest',
                   extent=(fbb.getMinX(), fbb.getMaxX(), fbb.getMinY(), fbb.getMaxY()))
        plt.gray()
        plt.savefig('foot2.png')

        sfoot = butils.symmetrizeFootprint(foot, 355, 227)

        mask2 = afwImg.MaskU(fbb.getWidth(), fbb.getHeight())
        mask2.setXY0(fbb.getMinX(), fbb.getMinY())
        afwDet.setMaskFromFootprint(mask2, sfoot, 1)

        plt.clf()
        plt.imshow(mask2.getArray(), origin='lower', interpolation='nearest',
                   extent=(fbb.getMinX(), fbb.getMaxX(), fbb.getMinY(), fbb.getMaxY()))
        plt.gray()
        plt.savefig('sfoot3.png')
开发者ID:dr-guangtou,项目名称:hs_hsc,代码行数:28,代码来源:symmFootprint.py

示例15: test

def test():

    from PIL import Image
    import numpy
    import pylab

    import os
    p = r'C:\repository\research_code\gwb_cropped\gwb_cropped'

    imlist = [p+'/'+f for f in os.listdir(p) if 'jpg' in f]

    im = numpy.array(Image.open(imlist[0])) #open one image to get the size
    m,n = im.shape[0:2] #get the size of the images
    imnbr = len(imlist) #get the number of images

#create matrix to store all flattened images
    immatrix = numpy.array([numpy.array(Image.open(imlist[i])).flatten() for i in range(imnbr)],'f')

#perform PCA
    V,S,immean = pca(immatrix)

#mean image and first mode of variation
    immean = immean.reshape(m,n)
    mode = V[0].reshape(m,n)

#show the images
    pylab.figure()
    pylab.gray()
    pylab.imshow(immean)

    pylab.figure()
    pylab.gray()
    pylab.imshow(mode)

    pylab.show()
开发者ID:bhattsachin,项目名称:PatternRecognition,代码行数:35,代码来源:pca.py


注:本文中的pylab.gray函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。