Directly saving a figure to disk without rendering first on the screen

六眼飞鱼酱① 提交于 2019-12-12 01:13:01

问题


I currently have code like the following:

import os
import numpy as np
import pylab 

import matplotlib.pyplot as plt
import matplotlib.cm as cm    
from matplotlib.patches import Polygon  
import numpy as np

...

# Read my image
img = matplotlib.image.imread(p_image)

# Render it, move the coordinates' origin to the upper left corner
plt.imshow(np.flipud(img), cmap=cm.Greys_r,origin='upper')

# Overlay a polygon
p = Polygon( zip(xs,ys), alpha=0.2)
plt.gca().add_artist(p)

# Save it to disk
plt.savefig(p_image_output)

How can I directly save this figure to disk without rendering it first on the screen? (notice that I would like the figure to keep the properties specified in the three arguments that I pass to imshow)


回答1:


Unless you are using ipython --pylab, the figure should only appear on screen if you do a show() or draw(). If you don't want it to be shown on the screen, just make sure you are not doing any of those calls.

Alternatively, you can use a non-interactive backend in matplotlib. For example, the Agg backend. Just make sure you have the following set in your ~/.matplotlib/matplotlibrc file:

backend      : Agg

Keep in mind that using this backend you'll never see anything on screen. If you use ipython, you can keep the configuration file and have an interactive backend by calling --pylab with a specific backend. For example:

ipython --pylab=qt



回答2:


One way is to set the matplotlib backend to something without interactive support. A standard way is to insert the following lines before you start using or importing from other parts of matplotlib:

import matplotlib
matplotlib.use('Agg')

The standard backend is TkAgg, which uses "agg" ("anti-grain geometry") rendering with a Tk interactive event loop. Using Agg does the same type of figure rendering, but without showing anything on the screen.

Note that, once you change the backend, matplotlib may not be able to switch it back. So this works best if you know you don’t want to plot anything on the screen in this script.



来源:https://stackoverflow.com/questions/13575659/directly-saving-a-figure-to-disk-without-rendering-first-on-the-screen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!