diff --git a/skimage/io/_plugins/pil_plugin.py b/skimage/io/_plugins/pil_plugin.py index e8f302e8..5018be49 100644 --- a/skimage/io/_plugins/pil_plugin.py +++ b/skimage/io/_plugins/pil_plugin.py @@ -52,7 +52,7 @@ def imread(fname, dtype=None, img_num=None, **kwargs): site = "http://pillow.readthedocs.org/en/latest/installation.html#external-libraries" raise ValueError('Could not load "%s"\nPlease see documentation at: %s' % (fname, site)) else: - return pil_to_ndarray(im, dtype=dtype) + return pil_to_ndarray(im, dtype=dtype, img_num=img_num) def pil_to_ndarray(im, dtype=None, img_num=None): @@ -64,6 +64,7 @@ def pil_to_ndarray(im, dtype=None, img_num=None): """ frames = [] + grayscale = None i = 0 while 1: try: @@ -71,23 +72,29 @@ def pil_to_ndarray(im, dtype=None, img_num=None): except EOFError: break - # seeking must be done sequentially - if img_num and not i == img_num: + frame = im + + if not img_num is None and img_num != i: + im.getdata()[0] i += 1 continue - frame = im if im.mode == 'P': - if _palette_is_grayscale(im): + if grayscale is None: + grayscale = _palette_is_grayscale(im) + + if grayscale: frame = im.convert('L') else: frame = im.convert('RGB') + elif im.mode == '1': frame = im.convert('L') elif 'A' in im.mode: frame = im.convert('RGBA') + if im.mode.startswith('I;16'): shape = im.size dtype = '>u2' if im.mode.endswith('B') else ' 1: + if img_num is None and len(frames) > 1: return np.array(frames) - else: + elif frames: return frames[0] + elif img_num: + raise IndexError('Could not find image #%s' % img_num) def _palette_is_grayscale(pil_image): diff --git a/skimage/io/collection.py b/skimage/io/collection.py index b7df8a3a..6a59b22c 100644 --- a/skimage/io/collection.py +++ b/skimage/io/collection.py @@ -210,12 +210,12 @@ class ImageCollection(object): else: i = 0 while True: - i += 1 - index.append((fname, i)) try: im.seek(i) except EOFError: break + index.append((fname, i)) + i += 1 if hasattr(im, 'fp') and im.fp: im.fp.close() diff --git a/skimage/io/tests/test_pil.py b/skimage/io/tests/test_pil.py index 02b3a4b8..cd9cbd21 100644 --- a/skimage/io/tests/test_pil.py +++ b/skimage/io/tests/test_pil.py @@ -170,6 +170,14 @@ def test_all_mono(): mono_check('pil', 'tiff') +def test_multi_page_gif(): + img = imread(os.path.join(data_dir, 'no_time_for_that.gif')) + assert img.shape == (24, 280, 500, 3), img.shape + img2 = imread(os.path.join(data_dir, 'no_time_for_that.gif'), + img_num=5) + assert img2.shape == (280, 500, 3) + assert_allclose(img[5], img2) + class TestSaveTIF: def roundtrip(self, dtype, x): f = NamedTemporaryFile(suffix='.tif')