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


Python image.thumbnail函数代码示例

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


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

示例1: make_population_map_file

 def make_population_map_file(self):
     if not os.path.exists(workspace_path(scenario_filename())):
         os.makedirs(workspace_path(scenario_filename()))
     print("Calculating a new Population Map")
     fig = population_results_map()
     FigureCanvas(fig).print_png(self.path)
     thumbnail(self.path, self.thumb_path, scale=0.1923)
     print("Finished Population Map")
开发者ID:NAVADMC,项目名称:ADSM,代码行数:8,代码来源:interactive_graphing.py

示例2: population_thumbnail_png

def population_thumbnail_png(request, second_try=False):
    path = workspace_path(scenario_filename() + '/population_map.png')
    thumb_path = workspace_path(scenario_filename() + '/population_thumbnail.png')
    try:
        with open(thumb_path, "rb") as f:
            return HttpResponse(f.read(), content_type="image/png")
    except IOError:
        if os.path.exists(path):
            if second_try:
               sleep(1) 
            thumbnail(path, thumb_path, scale=0.1923)  # create the thumbnail
            return population_thumbnail_png(request, second_try=True)
        else:
            sleep(5)
            return population_thumbnail_png(request, second_try=False)
开发者ID:NAVADMC,项目名称:ADSM,代码行数:15,代码来源:interactive_graphing.py

示例3: generate_thumbnails

def generate_thumbnails(thumbnails_dir, images_dir, scale=0.3):
    """
    Generate thumbnails into `thumbnails_dir` corresponding to images in
    `images_dir`.
    """
    ensure_path(thumbnails_dir + os.path.sep)

    output('generating thumbnails...')
    filenames = glob.glob(os.path.join(images_dir, '*.png'))
    for fig_filename in filenames:
        ebase = fig_filename.replace(sfepy.data_dir, '').lstrip(os.path.sep)
        output('"%s"' % ebase)

        base = os.path.basename(fig_filename)
        thumb_filename = os.path.join(thumbnails_dir, base)

        image.thumbnail(fig_filename, thumb_filename, scale=scale)

    output('...done')
开发者ID:frankipod,项目名称:sfepy,代码行数:19,代码来源:gen_gallery.py

示例4: convertImage

	def convertImage(self, thumbpath, plotspath, thumbscale):
		os.chdir(thumbpath)	# cd into thumbnails dir
		if (thumbpath == plotspath):
			print "Image/thumbnail paths match: NOT removing current images..."
		else:
			print "Image/thumbnail paths DO NOT match: removing previous images..."
			thmfiles = glob.glob(thumbpath+"*")
			for f in thmfiles:
				os.remove(f)	# rm tmp thumbnails from Thumbnails dir

		# read from output plots dir
		imgfiles = glob.glob(plotspath+"*")
		print "thumbscale = " + str(thumbscale) 
		cnt = 0	
		for f in imgfiles:
			tmp = re.split('/', f)
			tmplen = len(tmp)
			fname = tmp[tmplen-1].strip()	# pull image name
			tmp = re.split('\.', fname)
			fout = tmp[1].strip()	# pull station name
			fout = fout + "_24hr.png"	# append png
			img.thumbnail(f, fout, scale=thumbscale)
			cnt = cnt + 1
		print "num thumbnails = " + str(cnt) + "\n"
开发者ID:agonzales-usgs,项目名称:HeliPlotAPI,代码行数:24,代码来源:createThumbnails.py

示例5: write_example

def write_example(src_name, src_dir, rst_dir, cfg):
    """Write rst file from a given python example.

    Parameters
    ----------
    src_name : str
        Name of example file.
    src_dir : 'str'
        Source directory for python examples.
    rst_dir : 'str'
        Destination directory for rst files generated from python examples.
    cfg : config object
        Sphinx config object created by Sphinx.
    """
    last_dir = src_dir.psplit()[-1]
    # to avoid leading . in file names, and wrong names in links
    if last_dir == '.' or last_dir == 'examples':
        last_dir = Path('')
    else:
        last_dir += '_'

    src_path = src_dir.pjoin(src_name)
    example_file = rst_dir.pjoin(src_name)
    shutil.copyfile(src_path, example_file)

    image_dir = rst_dir.pjoin('images')
    thumb_dir = image_dir.pjoin('thumb')
    image_dir.makedirs()
    thumb_dir.makedirs()

    base_image_name = os.path.splitext(src_name)[0]
    image_path = image_dir.pjoin(base_image_name + '_{0}.png')

    basename, py_ext = os.path.splitext(src_name)
    rst_path = rst_dir.pjoin(basename + cfg.source_suffix)

    if _plots_are_current(src_path, image_path) and rst_path.exists:
        return

    flags = cfg.plot2rst_flags.copy()
    blocks, new_flags = split_code_and_text_blocks(example_file)
    flags.update(new_flags)

    while True:
        head = blocks[0][2]
        if head.startswith('#!') or head.startswith(FLAG_PREFIX):
            blocks.pop(0) # don't add shebangs or flags to rst file.
        else:
            break

    # Note that `process_blocks` executes the source, so plots are now 'active'
    figure_list, rst = process_blocks(blocks, src_path, image_path, cfg)

    rst_link = '.. _example_%s:\n\n' % (last_dir + src_name)
    example_rst = ''.join([rst_link, rst])

    has_inline_plots = any(cfg.plot2rst_plot_tag in b[2] for b in blocks)
    if not has_inline_plots and flags['auto_plots']:
        # Show all plots at the end of the example
        if len(plt.get_fignums()) > 0:
            figure_list = save_all_figures(image_path)
            img_blocks = [IMAGE_TEMPLATE % f.lstrip('/') for f in figure_list]
            example_rst += ''.join(img_blocks)
    plt.close('all')

    example_rst += CODE_LINK.format(src_name)

    f = open(rst_path,'w')
    f.write(example_rst)
    f.flush()

    thumb_path = thumb_dir.pjoin(src_name[:-3] + '.png')
    if figure_list:
        first_image_file = image_dir.pjoin(figure_list[0].lstrip('/'))
        if first_image_file.exists:
            thumb_scale = cfg.plot2rst_thumb_scale
            image.thumbnail(first_image_file, thumb_path, thumb_scale)

    if not thumb_path.exists:
        if cfg.plot2rst_default_thumb is None:
            print "WARNING: No plots found and default thumbnail not defined."
            print "Specify 'plot2rst_default_thumb' in Sphinx config file."
        else:
            shutil.copy(cfg.plot2rst_default_thumb, thumb_path)
开发者ID:gcalmettes,项目名称:mpltools,代码行数:84,代码来源:plot2rst.py

示例6: gen_gallery

def gen_gallery(app, doctree):
    if app.builder.name != 'html':
        return

    outdir = app.builder.outdir

    rootdir = os.path.join('plot_directive','example_code')

    # images we want to skip for the gallery because they are an unusual
    # size that doesn't layout well in a table, or because they may be
    # redundant with other images or uninteresting
    skips = set([
        'mathtext_examples',
        'matshow_02',
        'matshow_03',
        'matplotlib_icon',
        ])

    data = []
    thumbnails = {}

    for subdir in ('graphics', ):
        origdir = os.path.join(os.path.dirname(outdir), rootdir, subdir)
        thumbdir = os.path.join(outdir, rootdir, subdir, 'thumbnails')
        if not os.path.exists(thumbdir):
            os.makedirs(thumbdir)
        for filename in sorted(glob.glob(os.path.join(origdir, '*.png'))):
            if filename.endswith("hires.png"):
                continue

            path, filename = os.path.split(filename)
            basename, ext = os.path.splitext(filename)
            if basename in skips:
                continue

            # Create thumbnails based on images in tmpdir, and place
            # them within the build tree
            orig_path = str(os.path.join(origdir, filename))
            thumb_path = str(os.path.join(thumbdir, filename))
            if out_of_date(orig_path, thumb_path) or True:
                thumbnails[orig_path] = thumb_path

            m = multiimage.match(basename)
            if m is None:
                pyfile = '%s.py'%basename
            else:
                basename = m.group(1)
                pyfile = '%s.py'%basename

            data.append((subdir, basename,
                         os.path.join(rootdir, subdir, 'thumbnails', filename)))

    link_template = """\
    <a href="%(href)s"><img src="%(thumb_file)s" border="0" alt="%(alternative_text)s"/></a>
    """

    random_image_content_template = '''
// This file was automatically generated by gen_gallery.py & should not be modified directly.

images = new Array();

%s

'''

    random_image_template = "['%(thumbfile)s', '%(full_image)s', '%(link)s', 'Iris examples.'];"
    random_image_join = 'images[%s] = %s'

    if len(data) == 0:
        warnings.warn("No thumbnails were found")
        return

    rows = []
    random_image = []
    for (subdir, basename, thumbfile) in data:
        if thumbfile is not None:
            link = 'examples/%s/%s.html#%s'%(subdir, basename, os.path.splitext(os.path.basename(thumbfile))[0].replace('_', '-'))
            rows.append(link_template % {'href': link, 'thumb_file': thumbfile, 'alternative_text': basename})
            random_image.append(random_image_template % {'link':link, 'thumbfile':thumbfile, 'basename':basename, 'full_image':'_images/' + os.path.basename(thumbfile)} )

    random_image_content = random_image_content_template % '\n'.join([random_image_join % (i, line) for i, line in enumerate(random_image)])
    random_image_script_path = os.path.join(app.builder.srcdir, '_static', 'random_image.js')
    file(random_image_script_path, 'w').write(random_image_content)


    # Only write out the file if the contents have actually changed.
    # Otherwise, this triggers a full rebuild of the docs
    content = template%'\n'.join(rows)
    gallery_path = os.path.join(app.builder.srcdir, '_templates', 'gallery.html')
    if os.path.exists(gallery_path):
        fh = file(gallery_path, 'r')
        regenerate = fh.read() != content
        fh.close()
    else:
        regenerate = True
    if regenerate:
        fh = file(gallery_path, 'w')
        fh.write(content)
        fh.close()

#.........这里部分代码省略.........
开发者ID:qingu,项目名称:iris,代码行数:101,代码来源:gen_gallery.py

示例7: generate_file_rst


#.........这里部分代码省略.........
    stdout_path = os.path.join(image_dir, "stdout_%s.txt" % base_image_name)
    time_path = os.path.join(image_dir, "time_%s.txt" % base_image_name)
    thumb_file = os.path.join(thumb_dir, fname[:-3] + ".png")
    time_elapsed = 0
    if plot_gallery and fname.startswith("plot"):
        # generate the plot as png image if file name
        # starts with plot and if it is more recent than an
        # existing image.
        first_image_file = image_path % 1
        if os.path.exists(stdout_path):
            stdout = open(stdout_path).read()
        else:
            stdout = ""
        if os.path.exists(time_path):
            time_elapsed = float(open(time_path).read())

        if not os.path.exists(first_image_file) or os.stat(first_image_file).st_mtime <= os.stat(src_file).st_mtime:
            # We need to execute the code
            print "plotting %s" % fname
            t0 = time()
            import matplotlib.pyplot as plt

            plt.close("all")
            cwd = os.getcwd()
            try:
                # First CD in the original example dir, so that any file
                # created by the example get created in this directory
                orig_stdout = sys.stdout
                os.chdir(os.path.dirname(src_file))
                my_buffer = StringIO()
                my_stdout = Tee(sys.stdout, my_buffer)
                sys.stdout = my_stdout
                my_globals = {"pl": plt}
                execfile(os.path.basename(src_file), my_globals)
                time_elapsed = time() - t0
                sys.stdout = orig_stdout
                my_stdout = my_buffer.getvalue()
                if "__doc__" in my_globals:
                    # The __doc__ is often printed in the example, we
                    # don't with to echo it
                    my_stdout = my_stdout.replace(my_globals["__doc__"], "")
                my_stdout = my_stdout.strip()
                if my_stdout:
                    stdout = "**Script output**::\n\n  %s\n\n" % ("\n  ".join(my_stdout.split("\n")))
                open(stdout_path, "w").write(stdout)
                open(time_path, "w").write("%f" % time_elapsed)
                os.chdir(cwd)

                # In order to save every figure we have two solutions :
                # * iterate from 1 to infinity and call plt.fignum_exists(n)
                #   (this requires the figures to be numbered
                #    incrementally: 1, 2, 3 and not 1, 2, 5)
                # * iterate over [fig_mngr.num for fig_mngr in
                #   matplotlib._pylab_helpers.Gcf.get_all_fig_managers()]
                for fig_num in (fig_mngr.num for fig_mngr in matplotlib._pylab_helpers.Gcf.get_all_fig_managers()):
                    # Set the fig_num figure as the current figure as we can't
                    # save a figure that's not the current figure.
                    plt.figure(fig_num)
                    plt.savefig(image_path % fig_num)
                    figure_list.append(image_fname % fig_num)
            except:
                print 80 * "_"
                print "%s is not compiling:" % fname
                traceback.print_exc()
                print 80 * "_"
            finally:
                os.chdir(cwd)
                sys.stdout = orig_stdout

            print " - time elapsed : %.2g sec" % time_elapsed
        else:
            figure_list = [f[len(image_dir) :] for f in glob.glob(image_path % "[1-9]")]
            # for f in glob.glob(image_path % '*')]

        # generate thumb file
        this_template = plot_rst_template
        from matplotlib import image

        if os.path.exists(first_image_file):
            image.thumbnail(first_image_file, thumb_file, 0.2)

    if not os.path.exists(thumb_file):
        # create something not to replace the thumbnail
        shutil.copy("images/blank_image.png", thumb_file)

    docstring, short_desc, end_row = extract_docstring(example_file)

    # Depending on whether we have one or more figures, we're using a
    # horizontal list or a single rst call to 'image'.
    if len(figure_list) == 1:
        figure_name = figure_list[0]
        image_list = SINGLE_IMAGE % figure_name.lstrip("/")
    else:
        image_list = HLIST_HEADER
        for figure_name in figure_list:
            image_list += HLIST_IMAGE_TEMPLATE % figure_name.lstrip("/")

    f = open(os.path.join(target_dir, fname[:-2] + "rst"), "w")
    f.write(this_template % locals())
    f.flush()
开发者ID:nazli-fd,项目名称:scikit-learn,代码行数:101,代码来源:gen_rst.py

示例8: generate_file_rst


#.........这里部分代码省略.........
                                    os.stat(src_file).st_mtime):
            # We need to execute the code
            print('plotting %s' % fname)
            t0 = time()
            import matplotlib.pyplot as plt
            plt.close('all')
            cwd = os.getcwd()
            try:
                # First CD in the original example dir, so that any file
                # created by the example get created in this directory
                orig_stdout = sys.stdout
                os.chdir(os.path.dirname(src_file))
                my_buffer = StringIO()
                my_stdout = Tee(sys.stdout, my_buffer)
                sys.stdout = my_stdout
                my_globals = {'pl': plt}
                execfile(os.path.basename(src_file), my_globals)
                time_elapsed = time() - t0
                sys.stdout = orig_stdout
                my_stdout = my_buffer.getvalue()
                if '__doc__' in my_globals:
                    # The __doc__ is often printed in the example, we
                    # don't with to echo it
                    my_stdout = my_stdout.replace(
                                            my_globals['__doc__'],
                                            '')
                my_stdout = my_stdout.strip()
                if my_stdout:
                    stdout = '**Script output**::\n\n  %s\n\n' % (
                        '\n  '.join(my_stdout.split('\n')))
                open(stdout_path, 'w').write(stdout)
                open(time_path, 'w').write('%f' % time_elapsed)
                os.chdir(cwd)

                # In order to save every figure we have two solutions :
                # * iterate from 1 to infinity and call plt.fignum_exists(n)
                #   (this requires the figures to be numbered
                #    incrementally: 1, 2, 3 and not 1, 2, 5)
                # * iterate over [fig_mngr.num for fig_mngr in
                #   matplotlib._pylab_helpers.Gcf.get_all_fig_managers()]
                for fig_num in (fig_mngr.num for fig_mngr in
                        matplotlib._pylab_helpers.Gcf.get_all_fig_managers()):
                    # Set the fig_num figure as the current figure as we can't
                    # save a figure that's not the current figure.
                    plt.figure(fig_num)
                    plt.savefig(image_path % fig_num)
                    figure_list.append(image_fname % fig_num)
                for canvas in ROOT.gROOT.GetListOfCanvases():
                    maybe_root_filename = os.path.join(os.path.dirname(src_file), canvas.name)
                    if os.path.isfile(maybe_root_filename):
                        os.rename(maybe_root_filename, os.path.join(image_dir, canvas.name))
                        figure_list.append(canvas.name)
                        canvas.Close()
                    else:
                        canvas.SaveAs(root_image_path % root_fig_num)
                        canvas.Close()
                        figure_list.append(root_image_fname % root_fig_num)
                        root_fig_num += 1
            except:
                print(80 * '_')
                print('%s is not compiling:' % fname)
                traceback.print_exc()
                print(80 * '_')
            finally:
                os.chdir(cwd)
                sys.stdout = orig_stdout

            print(" - time elapsed : %.2g sec" % time_elapsed)
        else:
            figure_list = [f[len(image_dir):]
                            for f in glob.glob(image_path % '[1-9]')]
                            #for f in glob.glob(image_path % '*')]

        # generate thumb file
        this_template = plot_rst_template
        from matplotlib import image
        if os.path.exists(first_image_file):
            image.thumbnail(first_image_file, thumb_file, 0.2)
        elif os.path.exists(first_root_image_file):
            image.thumbnail(first_root_image_file, thumb_file, 0.2)

    if not os.path.exists(thumb_file):
        # create something not to replace the thumbnail
        shutil.copy('images/blank_image.png', thumb_file)

    docstring, short_desc, end_row = extract_docstring(example_file)

    # Depending on whether we have one or more figures, we're using a
    # horizontal list or a single rst call to 'image'.
    if len(figure_list) == 1:
        figure_name = figure_list[0]
        image_list = SINGLE_IMAGE % figure_name.lstrip('/')
    else:
        image_list = HLIST_HEADER
        for figure_name in figure_list:
            image_list += HLIST_IMAGE_TEMPLATE % figure_name.lstrip('/')

    f = open(os.path.join(target_dir, fname[:-2] + 'rst'), 'w')
    f.write(this_template % locals())
    f.flush()
开发者ID:ndawe,项目名称:root_numpy,代码行数:101,代码来源:gen_rst.py

示例9: makefig

def makefig(fullpath, outdir):
    """
    run a pyplot script<t and save the low and high res PNGs and a PDF in _static
    """

    fullpath = str(fullpath)  # todo, why is unicode breaking this

    print '    makefig: fullpath=%s, outdir=%s'%( fullpath, outdir)
    formats = [('png', 80),
               ('hires.png', 200),
               ('pdf', 50),
               ]

    basedir, fname = os.path.split(fullpath)
    basename, ext = os.path.splitext(fname)
    all_exists = True

    if basedir != outdir:
        shutil.copyfile(fullpath, os.path.join(outdir, fname))

    # Look for single-figure output files first
    for format, dpi in formats:
        outname = os.path.join(outdir, '%s.%s' % (basename, format))
        if out_of_date(fullpath, outname):
            all_exists = False
            break

    if all_exists:
        print '    already have %s'%fullpath
        return 1

    # Then look for multi-figure output files, assuming
    # if we have some we have all...
    i = 0
    while True:
        all_exists = True
        for format, dpi in formats:
            outname = os.path.join(outdir, '%s_%02d.%s' % (basename, i, format))
            if out_of_date(fullpath, outname):
                all_exists = False
                break
        if all_exists:
            i += 1
        else:
            break

    if i != 0:
        print '    already have %d figures for %s' % (i, fullpath)
        return i

    # We didn't find the files, so build them

    print '    building %s'%fullpath
    plt.close('all')    # we need to clear between runs
    matplotlib.rcdefaults()
    # Set a figure size that doesn't overflow typical browser windows
    matplotlib.rcParams['figure.figsize'] = (5.5, 4.5)

    try:
        runfile(fullpath)
    except:
	s = cbook.exception_to_str("Exception running plot %s" % fullpath)
        warnings.warn(s)
        return 0

    fig_managers = _pylab_helpers.Gcf.get_all_fig_managers()
    for i, figman in enumerate(fig_managers):
        for format, dpi in formats:
            if len(fig_managers) == 1:
                outname = basename
            else:
                outname = "%s_%02d" % (basename, i)
            outpath = os.path.join(outdir, '%s.%s' % (outname, format))
            try:
                figman.canvas.figure.savefig(outpath, dpi=dpi)
            except:
                s = cbook.exception_to_str("Exception running plot %s" % fullpath)
                warnings.warn(s)
                return 0

            if format=='png':
                thumbdir = os.path.join(outdir, 'thumbnails')
                if not os.path.exists(thumbdir):
                    os.makedirs(thumbdir)
                thumbfile = str('%s.png'%os.path.join(thumbdir, outname)     )
                if not os.path.exists(thumbfile):
                    figthumb = image.thumbnail(str(outpath), str(thumbfile), scale=0.3)
                    print '    makefig: saved thumbnail of %s to %s'%(outpath, thumbfile)

    return len(fig_managers)
开发者ID:mattfoster,项目名称:matplotlib,代码行数:90,代码来源:plot_directive.py

示例10: make_thumbnail

def make_thumbnail(args):
    image.thumbnail(args[0], args[1], 0.3)
开发者ID:KennethNielsen,项目名称:matplotlib,代码行数:2,代码来源:gen_gallery.py

示例11: collect

    def collect(self, blocks, figure_key="", subfig=0):
        '''collect one or more R figures.

        Plots are collected from all active devices.
        Plots are also collected from result-blocks
        containing a 'ggplot' attribute.

        1. save as png, hires-png and pdf
        2. save thumbnail
        3. insert rendering code at placeholders in output

        returns a map of place holder to placeholder text.
        '''
        # disable plotting if no rpy installed
        if R is None:
            return {}

        map_figure2text = {}

        # determine the image formats to create
        default_format, additional_formats = Utils.getImageFormats(
            self.display_options)
        all_formats = [default_format, ] + additional_formats
        image_options = Utils.getImageOptions(self.display_options)

        ##########################################
        ##########################################
        ##########################################
        # iterate over devices
        devices = R["dev.list"]()
        try:
            maxid = max(R["dev.list"]())
        except TypeError:
            maxid = 0

        for figid in range(2, maxid + 1):

            for id, format, dpi in all_formats:

                R["dev.set"](figid)

                outname = "%s_%02d" % (self.template_name, figid)
                outpath = os.path.join(self.outdir, '%s.%s' % (outname, format))

                if format.endswith("png"):
                    # for busy images there is a problem with figure margins
                    # simply increase dpi until it works.
                    R["dev.set"](figid)

                    width = height = 480 * dpi / 80
                    x = 0
                    while 1:
                        try:
                            R["dev.copy"](device=R.png,
                                          filename=outpath,
                                          res=dpi,
                                          width=width,
                                          height=height)
                            R["dev.off"]()
                        except rpy2.rinterface.RRuntimeError:
                            width *= 2
                            height *= 2
                            if x < 5:
                                continue
                        break

                elif format.endswith("svg"):
                    R["dev.copy"](device=R.svg,
                                  filename=outpath)
                    R["dev.off"]()

                elif format.endswith("eps"):
                    R["dev.copy"](device=R.postscript,
                                  paper='special',
                                  width=6,
                                  height=6,
                                  file=outpath,
                                  onefile=True)
                    R["dev.off"]()
                elif format.endswith("pdf"):
                    R["dev.copy"](device=R.pdf,
                                  paper='special',
                                  width=6,
                                  height=6,
                                  file=outpath,
                                  onefile=True)
                    R["dev.off"]()
                else:
                    raise ValueError("format '%s' not supported" % format)

                if not os.path.exists(outpath):
                    continue
                    # raise ValueError("rendering problem: image file was not be created: %s" % outpath)

                if format == 'png':
                    thumbdir = os.path.join(self.outdir, 'thumbnails')
                    try:
                        os.makedirs(thumbdir)
                    except OSError:
                        pass
#.........这里部分代码省略.........
开发者ID:AndreasHeger,项目名称:CGATReport,代码行数:101,代码来源:__init__.py

示例12: write_example

def write_example(src_name, src_dir, rst_dir, cfg):
    """Write rst file from a given python example.

    Parameters
    ----------
    src_name : str
        Name of example file.
    src_dir : 'str'
        Source directory for python examples.
    rst_dir : 'str'
        Destination directory for rst files generated from python examples.
    cfg : config object
        Sphinx config object created by Sphinx.
    """
    last_dir = src_dir.psplit()[-1]
    # to avoid leading . in file names, and wrong names in links
    if last_dir == "." or last_dir == "examples":
        last_dir = Path("")
    else:
        last_dir += "_"

    src_path = src_dir.pjoin(src_name)
    example_file = rst_dir.pjoin(src_name)
    shutil.copyfile(src_path, example_file)

    image_dir = rst_dir.pjoin("images")
    thumb_dir = image_dir.pjoin("thumb")
    image_dir.makedirs()
    thumb_dir.makedirs()

    base_image_name = os.path.splitext(src_name)[0]
    image_path = image_dir.pjoin(base_image_name + "_{0}.png")

    basename, py_ext = os.path.splitext(src_name)
    rst_path = rst_dir.pjoin(basename + cfg.source_suffix)

    if _plots_are_current(src_path, image_path) and rst_path.exists:
        return

    blocks = split_code_and_text_blocks(example_file)
    if blocks[0][2].startswith("#!"):
        blocks.pop(0)  # don't add shebang line to rst file.

    rst_link = ".. _example_%s:\n\n" % (last_dir + src_name)
    figure_list, rst = process_blocks(blocks, src_path, image_path, cfg)

    has_inline_plots = any(cfg.plot2rst_plot_tag in b[2] for b in blocks)
    if has_inline_plots:
        example_rst = "".join([rst_link, rst])
    else:
        # print first block of text, display all plots, then display code.
        first_text_block = [b for b in blocks if b[0] == "text"][0]
        label, (start, end), content = first_text_block
        figure_list = save_all_figures(image_path)
        rst_blocks = [IMAGE_TEMPLATE % f.lstrip("/") for f in figure_list]

        example_rst = rst_link
        example_rst += eval(content)
        example_rst += "".join(rst_blocks)
        code_info = dict(src_name=src_name, code_start=end)
        example_rst += LITERALINCLUDE.format(**code_info)

    example_rst += CODE_LINK.format(src_name)

    f = open(rst_path, "w")
    f.write(example_rst)
    f.flush()

    thumb_path = thumb_dir.pjoin(src_name[:-3] + ".png")
    first_image_file = image_dir.pjoin(figure_list[0].lstrip("/"))
    if first_image_file.exists:
        image.thumbnail(first_image_file, thumb_path, cfg.plot2rst_thumb_scale)

    if not thumb_path.exists:
        if cfg.plot2rst_default_thumb is None:
            print "WARNING: No plots found and default thumbnail not defined."
            print "Specify 'plot2rst_default_thumb' in Sphinx config file."
        else:
            shutil.copy(cfg.plot2rst_default_thumb, thumb_path)
开发者ID:arsenovic,项目名称:mpltools,代码行数:79,代码来源:plot2rst.py

示例13: gen_gallery

def gen_gallery(app, doctree):
    if app.builder.name not in ('html', 'htmlhelp'):
        return

    outdir = app.builder.outdir
    rootdir = 'plot_directive/mpl_examples'

    example_sections = list(app.builder.config.mpl_example_sections)
    for i, (subdir, title) in enumerate(example_sections):
        if subdir in exclude_example_sections:
            example_sections.pop(i)

    # images we want to skip for the gallery because they are an unusual
    # size that doesn't layout well in a table, or because they may be
    # redundant with other images or uninteresting
    skips = {'mathtext_examples',
             'matshow_02',
             'matshow_03',
             'matplotlib_icon'}

    thumbnails = {}
    rows = []
    toc_rows = []

    for subdir, title in example_sections:
        rows.append(header_template.format(title=title, section=subdir))
        toc_rows.append(toc_template.format(title=title, section=subdir))

        origdir = os.path.join('build', rootdir, subdir)
        thumbdir = os.path.join(outdir, rootdir, subdir, 'thumbnails')
        if not os.path.exists(thumbdir):
            os.makedirs(thumbdir)

        data = []

        for filename in sorted(glob.glob(os.path.join(origdir, '*.png'))):
            if filename.endswith("hires.png"):
                continue

            path, filename = os.path.split(filename)
            basename, ext = os.path.splitext(filename)
            if basename in skips:
                continue

            # Create thumbnails based on images in tmpdir, and place
            # them within the build tree
            orig_path = str(os.path.join(origdir, filename))
            thumb_path = str(os.path.join(thumbdir, filename))
            if out_of_date(orig_path, thumb_path) or True:
                thumbnails[orig_path] = thumb_path

            m = multiimage.match(basename)
            if m is not None:
                basename = m.group(1)

            data.append((subdir, basename,
                         os.path.join(rootdir, subdir, 'thumbnails', filename)))

        for (subdir, basename, thumbfile) in data:
            if thumbfile is not None:
                link = 'examples/%s/%s.html'%(subdir, basename)
                rows.append(link_template.format(link=link,
                                                 thumb=thumbfile,
                                                 basename=basename,
                                                 title=basename))

        if len(data) == 0:
            warnings.warn("No thumbnails were found in %s" % subdir)

        # Close out the <div> opened up at the top of this loop
        rows.append(u"</div>")

    content = gallery_template.format(toc=u'\n'.join(toc_rows),
                                      gallery=u'\n'.join(rows))

    # Only write out the file if the contents have actually changed.
    # Otherwise, this triggers a full rebuild of the docs

    gallery_path = os.path.join(app.builder.srcdir,
                                '_templates', 'gallery.html')
    if os.path.exists(gallery_path):
        with codecs.open(gallery_path, 'r', encoding='utf-8') as fh:
            regenerate = fh.read() != content
    else:
        regenerate = True

    if regenerate:
        with codecs.open(gallery_path, 'w', encoding='utf-8') as fh:
            fh.write(content)

    for key in app.builder.status_iterator(
            iter(thumbnails), "generating thumbnails... ",
            length=len(thumbnails)):
        if out_of_date(key, thumbnails[key]):
            image.thumbnail(key, thumbnails[key], 0.3)
开发者ID:AlexandreAbraham,项目名称:matplotlib,代码行数:95,代码来源:gen_gallery.py

示例14: generate_file_rst


#.........这里部分代码省略.........
            stdout = open(stdout_path).read()
        else:
            stdout = ''
        if os.path.exists(time_path):
            time_elapsed = float(open(time_path).read())

        if (not os.path.exists(first_image_file) or
                os.stat(first_image_file).st_mtime <=
                                    os.stat(src_file).st_mtime):
            # We need to execute the code
            print 'plotting %s' % fname
            t0 = time()
            import matplotlib.pyplot as plt
            plt.close('all')

            try:
                from mayavi import mlab
            except Exception, e:
                from enthought.mayavi import mlab
            mlab.close(all=True)

            cwd = os.getcwd()
            try:
                # First CD in the original example dir, so that any file
                # created by the example get created in this directory
                orig_stdout = sys.stdout
                os.chdir(os.path.dirname(src_file))
                my_buffer = StringIO()
                my_stdout = Tee(sys.stdout, my_buffer)
                sys.stdout = my_stdout
                my_globals = {'pl': plt}
                execfile(os.path.basename(src_file), my_globals)
                time_elapsed = time() - t0
                sys.stdout = orig_stdout
                my_stdout = my_buffer.getvalue()
                if '__doc__' in my_globals:
                    # The __doc__ is often printed in the example, we
                    # don't with to echo it
                    my_stdout = my_stdout.replace(
                                            my_globals['__doc__'],
                                            '')
                my_stdout = my_stdout.strip()
                if my_stdout:
                    output_lines = my_stdout.split('\n')
                    if len(output_lines) > MAX_NB_LINES_STDOUT:
                        output_lines = output_lines[:MAX_NB_LINES_STDOUT]
                        output_lines.append('...')
                    stdout = '**Script output**::\n\n  %s\n\n' % (
                      '\n  '.join(output_lines))
                open(stdout_path, 'w').write(stdout)
                open(time_path, 'w').write('%f' % time_elapsed)
                os.chdir(cwd)

                # In order to save every figure we have two solutions :
                # * iterate from 1 to infinity and call plt.fignum_exists(n)
                #   (this requires the figures to be numbered
                #    incrementally: 1, 2, 3 and not 1, 2, 5)
                # * iterate over [fig_mngr.num for fig_mngr in
                #   matplotlib._pylab_helpers.Gcf.get_all_fig_managers()]
                last_fig_num = 0
                for fig_num in (fig_mngr.num for fig_mngr in
                        matplotlib._pylab_helpers.Gcf.get_all_fig_managers()):
                    # Set the fig_num figure as the current figure as we can't
                    # save a figure that's not the current figure.
                    plt.figure(fig_num)
                    facecolor = plt.gcf().get_facecolor() # hack to keep black bg
                    if facecolor == (0.0, 0.0, 0.0, 1.0):
                        plt.savefig(image_path % fig_num, facecolor='black')
                    else:
                        plt.savefig(image_path % fig_num)
                    figure_list.append(image_fname % fig_num)
                    last_fig_num = fig_num

                e = mlab.get_engine()
                for scene in e.scenes:
                    last_fig_num += 1
                    mlab.savefig(image_path % last_fig_num)
                    figure_list.append(image_fname % last_fig_num)
                    mlab.close(scene)

            except:
                print 80 * '_'
                print '%s is not compiling:' % fname
                traceback.print_exc()
                print 80 * '_'
            finally:
                os.chdir(cwd)
                sys.stdout = orig_stdout

            print " - time elapsed : %.2g sec" % time_elapsed
        else:
            figure_list = [f[len(image_dir):]
                            for f in glob.glob(image_path % '[1-9]')]
                            #for f in glob.glob(image_path % '*')]

        # generate thumb file
        this_template = plot_rst_template
        from matplotlib import image
        if os.path.exists(first_image_file):
            image.thumbnail(first_image_file, thumb_file, 0.2)
开发者ID:starzynski,项目名称:mne-python,代码行数:101,代码来源:gen_rst.py

示例15: gen_gallery

def gen_gallery(app, doctree):
    if app.builder.name != 'html':
        return

    outdir = app.builder.outdir
    rootdir = 'examples'

    # Images we want to skip for the gallery because they are an unusual
    # size that doesn't layout well in a table, or because they may be
    # redundant with other images or uninteresting.
    skips = set([
        'mathtext_examples',
        'matshow_02',
        'matshow_03',
        'matplotlib_icon',
        ])

    thumbnails = {}
    rows = []
    random_image = []
    toc_rows = []

    link_template = ('<a href="{href}">'
                     '<img src="{thumb_file}" border="0"'
                     ' alt="{alternative_text}"/>'
                     '</a>')

    header_template = ('<div class="section" id="{}">'
                       '<h4>{}'
                       '<a class="headerlink" href="#{}"'
                       ' title="Permalink to this headline">&para;</a>'
                       '</h4>')

    toc_template = ('<li>'
                    '<a class="reference internal" href="#{}">{}</a>'
                    '</li>')

    random_image_content_template = '''
// This file was automatically generated by gen_gallery.py & should not be
// modified directly.

images = new Array();

{}

'''

    random_image_template = "['{thumbfile}', '{full_image}', '{link}'];"
    random_image_join = 'images[{}] = {}'

    dirs = ('General', 'Meteorology', 'Oceanography')

    for subdir in dirs:
        rows.append(header_template.format(subdir, subdir, subdir))
        toc_rows.append(toc_template.format(subdir, subdir))

        origdir = os.path.join(os.path.dirname(outdir), rootdir, subdir)
        if not os.path.exists(origdir):
            origdir = os.path.join(os.path.dirname(outdir), 'plot_directive',
                                   rootdir, subdir)
        thumbdir = os.path.join(outdir, rootdir, subdir, 'thumbnails')
        if not os.path.exists(thumbdir):
            os.makedirs(thumbdir)

        data = []

        for filename in sorted(glob.glob(os.path.join(origdir, '*.png'))):
            if filename.endswith('hires.png'):
                continue

            path, filename = os.path.split(filename)
            basename, ext = os.path.splitext(filename)
            if basename in skips:
                continue

            # Create thumbnails based on images in tmpdir, and place them
            # within the build tree.
            orig_path = str(os.path.join(origdir, filename))
            thumb_path = str(os.path.join(thumbdir, filename))
            if out_of_date(orig_path, thumb_path) or True:
                thumbnails[orig_path] = thumb_path

            m = multiimage.match(basename)
            if m is not None:
                basename = m.group(1)

            data.append((subdir, basename,
                         os.path.join(rootdir, subdir, 'thumbnails',
                                      filename)))

        for (subdir, basename, thumbfile) in data:
            if thumbfile is not None:
                anchor = os.path.basename(thumbfile)
                anchor = os.path.splitext(anchor)[0].replace('_', '-')
                link = 'examples/{}/{}.html#{}'.format(
                    subdir,
                    basename,
                    anchor)
                rows.append(link_template.format(
                    href=link,
#.........这里部分代码省略.........
开发者ID:marqh,项目名称:iris,代码行数:101,代码来源:gen_gallery.py


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