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


Python image.imsave函数代码示例

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


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

示例1: custom_imsave

def custom_imsave(path, image):
    imsave(path, image, cmap=cm.Greys_r)
    return

    ret = image.copy()
    ret = ret / (ret.max() / 255.0)
    imsave(path, ret.astype(int))
开发者ID:moritzschaefer,项目名称:dip2015,代码行数:7,代码来源:main.py

示例2: show_progress

def show_progress(x, net, title=None, handle=False, dname='', CLC=True, IF_SAVE=False):
    '''
    Helper function to show intermediate results during the gradient descent.

    :param x: vectorised image on which the gradient descent is performed
    :param net: caffe.Classifier object defining the network
    :param title: optional title of figuer
    :param handle: obtional return of figure handle
    :return: figure handle (optional)
    '''
    global index
    disp_image = (x.reshape(*net.blobs['data'].data.shape)[0].transpose(1,2,0)[:,:,::-1]-x.min())/(x.max()-x.min())
    if CLC:
    	clear_output()
    if disp_image.shape[2] == 1:
        plt.imshow(disp_image[:,:,0], cmap='gray')
        if IF_SAVE:
	        pimg.imsave(dname+str(index)+'.png',disp_image[:,:,0], cmap='gray')
	        index += 1
    else:
        plt.imshow(disp_image)
    if title != None:
        ax = plt.gca()
        ax.set_title(title)
    f = plt.gcf()
    display()
    plt.show()    
    if handle:
        return f
开发者ID:yeze322,项目名称:TextureGen,代码行数:29,代码来源:Misc.py

示例3: display_image

def display_image(image):
    import io
    from matplotlib.image import imsave
    from IPython import display
    buf = io.BytesIO()
    imsave(buf, image)
    return display.display_png(display.Image(buf.getvalue()))
开发者ID:Andor-Z,项目名称:scpy2,代码行数:7,代码来源:image.py

示例4: savePic2

def savePic2(fname, matrix, mode='normal'):
    if mode == 'normal':
        pimg.imsave(fname, matrix)
    elif mode == 'gray':
        pimg.imsave(fname, matrix, cmap=mlib.cm.gray)
    else:
        pass
开发者ID:yeze322,项目名称:ChineseCharCNNPrj,代码行数:7,代码来源:piclib.py

示例5: averager

def averager(imgpaths, width=500, height=600, alpha=False,
             blur_edges=False, out_filename='result.png', plot=False):
  size = (height, width)

  images = []
  point_set = []
  for path in imgpaths:
    img, points = load_image_points(path, size)
    if img is not None:
      images.append(img)
      point_set.append(points)

  ave_points = locator.average_points(point_set)
  num_images = len(images)
  result_images = np.zeros(images[0].shape, np.float32)
  for i in xrange(num_images):
    result_images += warper.warp_image(images[i], point_set[i],
                                       ave_points, size, np.float32)

  result_image = np.uint8(result_images / num_images)

  mask = blender.mask_from_points(size, ave_points)
  if blur_edges:
    blur_radius = 10
    mask = cv2.blur(mask, (blur_radius, blur_radius))
  if alpha:
    result_image = np.dstack((result_image, mask))
  mpimg.imsave(out_filename, result_image)

  if plot:
    plt.axis('off')
    plt.imshow(result_image)
    plt.show()
开发者ID:qwIvan,项目名称:stasm_build,代码行数:33,代码来源:averager.py

示例6: generate_label

def generate_label(num):
	for i in range(num):
		pagenum = i
		print "Label page num",pagenum
		infile = "./meas/"+"poly_44_"+str(pagenum)
		#read svg file and assemble
		svg_file = infile + ".svg"
		primlist,stafflist,barlist= svg2primlist(svg_file)
		primitive_assemble(primlist)
		#read xml file
		xml_file = infile + ".xml"
		score = converter.parse(xml_file)
		#score.show('text')
		#cut out png, and write out label for each column
		myimg = mpimg.imread(infile+'.png')
		extraspace = 30
		cur = myimg[stafflist[0]-extraspace:stafflist[4]+extraspace,barlist[0]:barlist[1]]
		pngname = infile+"_s"+".png"
		mpimg.imsave(pngname,cur)
		column_labels,range_labels = match_score2prim(score,primlist,stafflist,barlist,myimg,extraspace)
		labelfile = infile+"_col.txt"
		f = open(labelfile,"w")
		f.write(column_labels)
		f.close()
		rangefile = infile+"_s.txt"
		f2 = open(rangefile,"w")
		f2.write(range_labels)
		f2.close()
开发者ID:liang-chen,项目名称:omr_lstm,代码行数:28,代码来源:poly_assemble_measure.py

示例7: warp_report

def warp_report(in_file):
    """Plot the registration summary using nipy contours"""
    mni_file = op.join(os.environ["FSL_DIR"],
                       "data/standard/MNI152_T1_1mm_brain.nii.gz")
    mni_img = nib.load(mni_file)
    mni_data, mni_aff = mni_img.get_data(), mni_img.get_affine()
    sub_img = nib.load(in_file)
    sub_data, sub_aff = sub_img.get_data(), sub_img.get_affine()
    sub_data[sub_data < 1] = 0

    kwargs = dict(draw_cross=False, annotate=False)
    cut_coords = dict(x=(-45, -12, 12, 45),
                      y=(-55, -25, 5, 45),
                      z=(-30, -5, 20, 40))

    colors = sns.color_palette("bright")
    im_data = dict()
    for axis in ["x", "y", "z"]:
        f = plt.figure(figsize=(10, 2.5))
        coords = cut_coords[axis]
        slicer = viz.plot_anat(sub_data, sub_aff, slicer=axis,
                               cut_coords=coords, figure=f, **kwargs)
        slicer.contour_map(mni_data, mni_aff, colors=colors)
        fname = "slices_%s.png" % axis
        f.savefig(fname, facecolor="k", edgecolor="k")
        im_data[axis] = mplimg.imread(fname)

    concat_data = [im_data[axis] for axis in ["x", "y", "z"]]
    concat_data = np.concatenate(concat_data, axis=0)
    mplimg.imsave("warp_report.png", concat_data)
    return op.abspath("warp_report.png")
开发者ID:toddt,项目名称:lyman,代码行数:31,代码来源:anatwarp.py

示例8: _fetch_captchas_to_dir

def _fetch_captchas_to_dir(directory, num=1):
    plt.ion()
    plt.show()
    for i in range(num):
        img = _captcha_provider.fetch()
        plt.clf()
        plt.axis('off')
        plt.imshow(img)
        # http://stackoverflow.com/questions/12670101/matplotlib-ion-function
        # -fails-to-be-interactive
        # https://github.com/matplotlib/matplotlib/issues/1646/
        plt.show()
        plt.pause(1e-2)

        while True:
            seq = input('[{}] Enter the char sequence: '.format(i + 1))
            # To skip a CAPTCHA.
            # Warning: skipping may reduce the quality of the training set.
            if seq == _SEQ_SKIP:
                break
            seq = _captcha_provider.canonicalize_seq(seq)
            if not _captcha_provider.is_valid_seq(seq):
                print('Invalid sequence!')
            else:
                break
        if seq == _SEQ_SKIP:
            print('Skipped manually')
            continue
        path = os.path.join(directory, _add_suffix(seq))
        if os.path.isfile(path):
            print('Warning: char sequence already exists in dataset! Skipping')
        else:
            mpimg.imsave(path, img)
    plt.ioff()
开发者ID:xieyanfu,项目名称:bilibili-captcha,代码行数:34,代码来源:dataset_manager.py

示例9: saveVideo

def saveVideo(I, IDims, filename, FrameRate = 30, YCbCr = False, Normalize = False):
    #Overwrite by default
    if os.path.exists(filename):
        os.remove(filename)
    N = I.shape[0]
    if YCbCr:
        for i in range(N):
            frame = np.reshape(I[i, :], IDims)
            I[i, :] = ntsc2rgb(frame).flatten()
    if Normalize:
        I = I-np.min(I)
        I = I/np.max(I)
    for i in range(N):
        frame = np.reshape(I[i, :], IDims)
        frame[frame < 0] = 0
        frame[frame > 1] = 1
        mpimage.imsave("%s%i.png"%(TEMP_STR, i+1), frame)
    if os.path.exists(filename):
        os.remove(filename)
    #Convert to video using avconv
    command = [AVCONV_BIN,
                '-r', "%i"%FrameRate,
                '-i', TEMP_STR + '%d.png', 
                '-r', "%i"%FrameRate,
                '-b', '30000k', 
                filename]
    subprocess.call(command)
    #Clean up
    for i in range(N):
        os.remove("%s%i.png"%(TEMP_STR, i+1))
开发者ID:agoodweathercc,项目名称:TUMTopoTimeSeries2016,代码行数:30,代码来源:VideoTools.py

示例10: main

def main():

    # Check and parse arguments
    if len(sys.argv) < 2:
        print("Not enough arguments given. Need full path for the image file.")
        sys.exit()
    source = sys.argv[1]

    im_colors = { 'r':0, 'g':1, 'b':2}

    for filename in os.listdir(source):
        filepath = source + filename
        if os.path.splitext(filepath)[1] == '.jpg':

            # Load image
            im       = mpim.imread(filepath)
            im_color = im_colors[filename[-5]]

            # Switch color channel
            rows, cols               = im.shape
            im_colored               = np.zeros((rows, cols, 3))
            im_colored[:,:,im_color] = im / 255.

            # Save colored image
            mpim.imsave(os.path.splitext(filepath)[0] + '.png', im_colored,
                                                                format='PNG')
开发者ID:fgb,项目名称:ysb_tools,代码行数:26,代码来源:color_grayscale_images.py

示例11: save_image

    def save_image(self, filename, mode='rgb', antialiased=False):
        """Save view from all panels to disk

        Parameters
        ----------
        filename: string
            Path to new image file.
        mode : string
            Either 'rgb' (default) to render solid background, or 'rgba' to
            include alpha channel for transparent background.
        antialiased : bool
            Antialias the image (see :func:`mayavi.mlab.screenshot`
            for details; default False).

            .. warning::
               Antialiasing can interfere with ``rgba`` mode, leading to opaque
               background.

        Notes
        -----
        Due to limitations in TraitsUI, if multiple views or hemi='split'
        is used, there is no guarantee painting of the windows will
        complete before control is returned to the command line. Thus
        we strongly recommend using only one figure window (which uses
        a Mayavi figure to plot instead of TraitsUI) if you intend to
        script plotting commands.
        """
        im = self.screenshot(mode, antialiased)
        imsave(filename, im)
开发者ID:christianbrodbeck,项目名称:Eelbrain,代码行数:29,代码来源:_brain_object.py

示例12: imgHibrida

def imgHibrida():
    raiz = os.getcwd()
    filtro = gaussiana(9)
    alinear(Image.open(raiz + "\human.png"), Image.open(raiz + "\cat.png"))
    gato = mpimg.imread(raiz + "\cat.png")
    print gato.shape
    humano = mpimg.imread(raiz + "\humanAlign.png")

    gatoConv = lowFilter(gato, filtro)
    humanoConv = lowFilter(humano, filtro)
    gatoHighConv = highFilter(gato, gatoConv)

    plt.show()
    plt.imshow(gatoHighConv)
    plt.colorbar()
    plt.title("Gat(Convolution with hp)")

    plt.show()
    plt.imshow(humanoConv)
    plt.colorbar()
    plt.title("Human(Convolution with lp)")

    finalImage = gatoHighConv + humanoConv
    normalizar(finalImage)
    plt.show()
    plt.imshow(finalImage)
    plt.colorbar()
    plt.title("Hybrid Image")
    mpimg.imsave("HybridImage1.png", finalImage)
开发者ID:Yue93,项目名称:PID,代码行数:29,代码来源:practica1.py

示例13: main

def main():
  # parse command line arguments
  parser = argparse.ArgumentParser(description='Colorize pictures')
  parser.add_argument('greyImage', help='png image to be coloured')
  parser.add_argument('markedImage', help='png image with colour hints')
  parser.add_argument('output', help='png output file')
  parser.add_argument('-v', '--view', help='display image', action='store_true')
  args = parser.parse_args()

  # Note: when reading .png, division by 255. is not required
  # Note: when reading .bmp, division by 255. is required
  # TODO: make this more universal, i.e., support various image formats
  # read images
  greyImage = mpimg.imread(args.greyImage, format='png')
  markedImage = mpimg.imread(args.markedImage, format='png')
  
  # colorize
  colouredImage = colorize(greyImage, markedImage)
    
  # save output
  mpimg.imsave(args.output,colouredImage, format='png')
  
  # display output, if requested
  if args.view:
    plt.imshow(colouredImage)
    plt.show()
开发者ID:godfatherofpolka,项目名称:ColorizationUsingOptimizationInPython,代码行数:26,代码来源:colorizer.py

示例14: match_score2prim

def match_score2prim(score,primlist,stafflist,barlist,myimg):
	notelist = score.getElementsByClass('Part')[0].getElementsByClass('Measure')[0].getElementsByClass('Note')
	#read all stem primitives
	stemlist = []
	for i in primlist:
		if i.name == "stem":
			stemlist.append(i)
	stemlist.sort(key=lambda x:x.locbegin[0],reverse=False)
	#for i in stemlist:
	#	print i.locbegin[0]
	note_range = []
	cols = range(barlist[1]-barlist[0])#10 pixels per column, overlap by 5
	column_labels = [0 for i in range(len(cols))]
	for i in range(len(notelist)):
		dur_label = int(4*notelist[i].duration.quarterLength)
		pitch_label = notelist[i].pitch
		left,right = get_stem_box(stemlist[i])
		#note_range.append([x,x2])
		up = stafflist[0]-20
		down = stafflist[4]+20
		#print dur_label,left,right
		cur = myimg[up:down,int(left):int(right)]
		debugdir = "./debug/"
		if not os.path.exists(debugdir):
			os.makedirs(debugdir)
		pngname = "./debug/"+str(dur_label)+"_"+str(int(left))+".png"
		mpimg.imsave(pngname,cur)
		for j in range(int(left)-barlist[0],int(right)-barlist[0]):
			column_labels[j] = dur_label
	reply = ""
	for i in column_labels:
		reply += str(i) + " "
	reply += "\n"
	return reply
开发者ID:liang-chen,项目名称:omr_lstm,代码行数:34,代码来源:assemble_measure.py

示例15: post_process

	def post_process(self, sequence):
		# postprocess a sequence in some way

		sequence = np.array(sequence[self.params['n_steps']:])

		save_generated_example('generated.wav',np.array(sequence))
		mpimg.imsave('sequence.png',sequence)
开发者ID:hsin919,项目名称:music-rnn-tensorflow,代码行数:7,代码来源:build.py


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