2

How can I export numpy.ndarray as a graphics file (png, jpg, ...)?

When I try the following:

test = zeros((500, 750, 3), dtype=numpy.uint8)
imsave('out.png',test)

I get this error:

TypeError: from_bounds() takes exactly 4 arguments (5 given)

Below is the complete error output:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-ff0e3e551b72> in <module>()
----> 1 imsave('out.png',test)

/usr/lib/pymodules/python2.7/matplotlib/pyplot.pyc in imsave(*args, **kwargs)
   1751 @docstring.copy_dedent(_imsave)
   1752 def imsave(*args, **kwargs):
-> 1753     return _imsave(*args, **kwargs)
   1754 
   1755 def matshow(A, fignum=None, **kw):

/usr/lib/pymodules/python2.7/matplotlib/image.pyc in imsave(fname, arr, vmin, vmax, cmap, format, origin, dpi)
   1229 
   1230     figsize = [x / float(dpi) for x in arr.shape[::-1]]
-> 1231     fig = Figure(figsize=figsize, dpi=dpi, frameon=False)
   1232     canvas = FigureCanvas(fig)
   1233     im = fig.figimage(arr, cmap=cmap, vmin=vmin, vmax=vmax, origin=origin)

/usr/lib/pymodules/python2.7/matplotlib/figure.pyc in __init__(self, figsize, dpi, facecolor, edgecolor, linewidth, frameon, subplotpars)
    266         self.dpi_scale_trans = Affine2D()
    267         self.dpi = dpi
--> 268         self.bbox_inches = Bbox.from_bounds(0, 0, *figsize)
    269         self.bbox = TransformedBbox(self.bbox_inches, self.dpi_scale_trans)
    270 

TypeError: from_bounds() takes exactly 4 arguments (5 given)
ali_m
  • 71,714
  • 23
  • 223
  • 298
Martin Vegter
  • 136
  • 9
  • 32
  • 56

2 Answers2

4

The cause of the error you're seeing is this line in the traceback:

1230     figsize = [x / float(dpi) for x in arr.shape[::-1]]

Your array is 3-dimensional, so figsize will be a list of length 3. Later on, this list gets unpacked in the arguments to Bbox.from_bounds():

--> 268         self.bbox_inches = Bbox.from_bounds(0, 0, *figsize)

Bbox.from_bounds() expects 4 arguments, but since the length of figsize is 3, it will get 5 arguments instead, hence the error.

This bug only affects RGB(A) image arrays, and was fixed in this commit - If you update your version of matplotlib to 1.3.1 or newer, the problem will go away.

Of course, there are lots of other ways to save numpy arrays to image files, and you could always use PIL (as in @enrico.bascis's answer), or one of the other methods from the question that @JohnZwink linked to instead.

ali_m
  • 71,714
  • 23
  • 223
  • 298
3

You can use PIL:

import Image
import numpy as np

test = np.zeros((500, 750, 3), np.int8)
im = Image.fromarray(test, 'RGB')
im.save('test.png')
enrico.bacis
  • 30,497
  • 10
  • 86
  • 115