support for saving to file-like object in imsave

This commit is contained in:
Adam Wisniewski
2013-06-28 16:18:01 -04:00
parent 6d5c8cb299
commit 362d915399
2 changed files with 18 additions and 3 deletions
+6 -3
View File
@@ -71,9 +71,8 @@ def imsave(fname, arr, format_str=None):
values in [0, 255], whereas floating-point arrays must be
in [0, 1].
format_str: str
Format to save as, this is required if using a file-like object;
this is optional if fname is a string and the format can be
derived from the extension.
Format to save as, this is defaulted to PNG if using a file-like
object; this will be derived from the extension if fname is a string
Notes
-----
@@ -104,6 +103,10 @@ def imsave(fname, arr, format_str=None):
# Force all integers to bytes
arr = arr.astype(np.uint8)
# default to PNG if file-like object
if not isinstance(fname, basestring) and format_str is None:
format_str = "PNG"
img = Image.fromstring(mode, (arr.shape[1], arr.shape[0]), arr.tostring())
img.save(fname, format=format_str)
+12
View File
@@ -2,6 +2,7 @@ import os
from numpy.testing import *
import numpy as np
from StringIO import StringIO
import skimage.io as io
from skimage import data_dir
@@ -27,6 +28,17 @@ def test_imread_url():
image = io.imread(image_url)
assert image.shape == (512, 512)
def test_imsave_filelike():
image = np.array([[0, 0], [0, 0]], dtype=float)
s = StringIO()
# save to file-like object
io.imsave(s, image)
# read from file-like object
s.seek(0)
image = io.imread(s)
assert image.shape == (2, 2)
if __name__ == "__main__":
run_module_suite()