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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With