@@ -609,13 +609,29 @@ def imread(fname):
609
609
610
610
Return value is a MxNx4 array of 0-1 normalized floats
611
611
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
612
615
"""
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
+
613
625
handlers = {'png' :_image .readpng ,
614
626
}
615
627
basename , ext = os .path .splitext (fname )
616
628
ext = ext .lower ()[1 :]
629
+
617
630
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
619
635
620
636
handler = handlers [ext ]
621
637
return handler (fname )
@@ -632,6 +648,6 @@ def pil_to_array( pilImage ):
632
648
raise RuntimeError ('Unknown image mode' )
633
649
634
650
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 )
636
652
x .shape = im .size [1 ], im .size [0 ], 4
637
653
return x
0 commit comments