87
|
1
|
|
2 import Numeric, Image
|
|
3 """ Transforme une image PIL en objet numpy.array et vice versa"""
|
|
4
|
|
5
|
|
6 def image2array(im):
|
|
7 """ image vers array numpy"""
|
|
8 if im.mode not in ("L", "F"):
|
|
9 raise ValueError, "can only convert single-layer images"
|
|
10 if im.mode == "L":
|
|
11 a = Numeric.fromstring(im.tostring(), Numeric.UnsignedInt8)
|
|
12 else:
|
|
13 a = Numeric.fromstring(im.tostring(), Numeric.Float32)
|
|
14 a.shape = im.size[1], im.size[0]
|
|
15 return a
|
|
16
|
|
17 def array2image(a):
|
|
18 """ array numpy vers image"""
|
|
19 if a.typecode() == Numeric.UnsignedInt8:
|
|
20 mode = "L"
|
|
21 elif a.typecode() == Numeric.Float32:
|
|
22 mode = "F"
|
|
23 else:
|
|
24 raise ValueError, "unsupported image mode"
|
|
25 return Image.fromstring(mode, (a.shape[1], a.shape[0]), a.tostring())
|