From 362d915399cc9c77d9f8223004d0a5cc1b9cf295 Mon Sep 17 00:00:00 2001 From: Adam Wisniewski Date: Fri, 28 Jun 2013 16:18:01 -0400 Subject: [PATCH] support for saving to file-like object in imsave --- skimage/io/_plugins/pil_plugin.py | 9 ++++++--- skimage/io/tests/test_io.py | 12 ++++++++++++ 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/skimage/io/_plugins/pil_plugin.py b/skimage/io/_plugins/pil_plugin.py index 2247f3a1..3ce79c47 100644 --- a/skimage/io/_plugins/pil_plugin.py +++ b/skimage/io/_plugins/pil_plugin.py @@ -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) diff --git a/skimage/io/tests/test_io.py b/skimage/io/tests/test_io.py index 484784ee..5fa3e14a 100644 --- a/skimage/io/tests/test_io.py +++ b/skimage/io/tests/test_io.py @@ -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()