Merge pull request #1263 from blink1073/fix-load-imgnum

Fix handling of img_num in PIL Plugin
This commit is contained in:
Stefan van der Walt
2014-12-12 18:26:51 +02:00
3 changed files with 26 additions and 9 deletions
+16 -7
View File
@@ -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 '<u2'
@@ -105,10 +112,12 @@ def pil_to_ndarray(im, dtype=None, img_num=None):
if hasattr(im, 'fp') and im.fp:
im.fp.close()
if len(frames) > 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):
+2 -2
View File
@@ -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()
+8
View File
@@ -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')