Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 2881611

Browse files
committed
added pil support to imread
svn path=/branches/v0_91_maint/; revision=5258
1 parent d9e2ced commit 2881611

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

lib/matplotlib/image.py

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -609,13 +609,29 @@ def imread(fname):
609609
610610
Return value is a MxNx4 array of 0-1 normalized floats
611611
612+
matplotlib can only read PNGs natively, but if PIL is installed,
613+
it will use it to load the image and return an RGBA if possible
614+
which can be used with imshow
612615
"""
616+
617+
def pilread():
618+
'try to load the image with PIL or return None'
619+
try: import Image
620+
except ImportError: return None
621+
image = Image.open( fname )
622+
return pil_to_array(image)
623+
624+
613625
handlers = {'png' :_image.readpng,
614626
}
615627
basename, ext = os.path.splitext(fname)
616628
ext = ext.lower()[1:]
629+
617630
if ext not in handlers.keys():
618-
raise ValueError('Only know how to handled extensions: %s' % handlers.keys())
631+
im = pilread()
632+
if im is None:
633+
raise ValueError('Only know how to handle extensions: %s; with PIL installed matplotlib can handle more images' % handlers.keys())
634+
return im
619635

620636
handler = handlers[ext]
621637
return handler(fname)
@@ -632,6 +648,6 @@ def pil_to_array( pilImage ):
632648
raise RuntimeError('Unknown image mode')
633649

634650
x_str = im.tostring('raw',im.mode,0,-1)
635-
x = npy.fromstring(x_str,npy.uint8)
651+
x = np.fromstring(x_str,np.uint8)
636652
x.shape = im.size[1], im.size[0], 4
637653
return x

0 commit comments

Comments
 (0)