1

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)

Amelio Vazquez-Reina
  • 91,494
  • 132
  • 359
  • 564

2 Answers2

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.

illya
  • 765
  • 5
  • 8
2

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
tiago
  • 22,602
  • 12
  • 72
  • 88