We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Python 3 compatibility problem with Image loading
Loading an Image using the `load_img` results in an error.

```
Traceback (most recent call last):
  File "keras/autoencoder.py", line 45, in <module>
    X_train, Y_train, X_test, Y_test, nb_classes = io.load_images(join(DATA_DIR, 'dataset0'))
  File "/home/jnphilipp/Documents/cnn/hieroglyphs/keras/utils/io.py", line 27, in load_images
    X_train.append(img_to_array(load_img(picture, True)))
  File "/home/jnphilipp/.local/lib/python3.4/site-packages/Keras-0.1.2-py3.4.egg/keras/preprocessing/image.py", line 107, in load_img
  File "/home/jnphilipp/.local/lib/python3.4/site-packages/PIL/Image.py", line 2330, in open
    % (filename if filename else fp))
OSError: cannot identify image file <_io.TextIOWrapper name='/home/jnphilipp/Documents/cnn/hieroglyphs/data/dataset0/train/P1_train0.png' mode='r' encoding='ISO-8859-1'>
```


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `keras/preprocessing/image.py`
Content:
```
1 from __future__ import absolute_import
2 
3 import numpy as np
4 import re
5 from scipy import ndimage
6 from scipy import linalg
7 
8 from os import listdir
9 from os.path import isfile, join
10 import random, math
11 from six.moves import range
12 
13 '''
14     Fairly basic set of tools for realtime data augmentation on image data.
15     Can easily be extended to include new transforms, new preprocessing methods, etc...
16 '''
17 
18 def random_rotation(x, rg, fill_mode="nearest", cval=0.):
19     angle = random.uniform(-rg, rg)
20     x = ndimage.interpolation.rotate(x, angle, axes=(1,2), reshape=False, mode=fill_mode, cval=cval)
21     return x
22 
23 def random_shift(x, wrg, hrg, fill_mode="nearest", cval=0.):
24     crop_left_pixels = 0
25     crop_right_pixels = 0
26     crop_top_pixels = 0
27     crop_bottom_pixels = 0
28 
29     original_w = x.shape[1]
30     original_h = x.shape[2]
31 
32     if wrg:
33         crop = random.uniform(0., wrg)
34         split = random.uniform(0, 1)
35         crop_left_pixels = int(split*crop*x.shape[1])
36         crop_right_pixels = int((1-split)*crop*x.shape[1])
37 
38     if hrg:
39         crop = random.uniform(0., hrg)
40         split = random.uniform(0, 1)
41         crop_top_pixels = int(split*crop*x.shape[2])
42         crop_bottom_pixels = int((1-split)*crop*x.shape[2])
43 
44     x = ndimage.interpolation.shift(x, (0, crop_left_pixels, crop_top_pixels), mode=fill_mode, cval=cval)
45     return x
46 
47 def horizontal_flip(x):
48     for i in range(x.shape[0]):
49         x[i] = np.fliplr(x[i])
50     return x
51 
52 def vertical_flip(x):
53     for i in range(x.shape[0]):
54         x[i] = np.flipud(x[i])
55     return x
56 
57 
58 def random_barrel_transform(x, intensity):
59     # TODO
60     pass
61 
62 def random_shear(x, intensity):
63     # TODO
64     pass
65 
66 def random_channel_shift(x, rg):
67     # TODO
68     pass
69 
70 def random_zoom(x, rg, fill_mode="nearest", cval=0.):
71     zoom_w = random.uniform(1.-rg, 1.)
72     zoom_h = random.uniform(1.-rg, 1.)
73     x = ndimage.interpolation.zoom(x, zoom=(1., zoom_w, zoom_h), mode=fill_mode, cval=cval)
74     return x # shape of result will be different from shape of input!
75 
76 
77 
78 
79 def array_to_img(x, scale=True):
80     from PIL import Image
81     x = x.transpose(1, 2, 0) 
82     if scale:
83         x += max(-np.min(x), 0)
84         x /= np.max(x)
85         x *= 255
86     if x.shape[2] == 3:
87         # RGB
88         return Image.fromarray(x.astype("uint8"), "RGB")
89     else:
90         # grayscale
91         return Image.fromarray(x[:,:,0].astype("uint8"), "L")
92 
93 
94 def img_to_array(img):
95     x = np.asarray(img, dtype='float32')
96     if len(x.shape)==3:
97         # RGB: height, width, channel -> channel, height, width
98         x = x.transpose(2, 0, 1)
99     else:
100         # grayscale: height, width -> channel, height, width
101         x = x.reshape((1, x.shape[0], x.shape[1]))
102     return x
103 
104 
105 def load_img(path, grayscale=False):
106     from PIL import Image
107     img = Image.open(open(path))
108     if grayscale:
109         img = img.convert('L')
110     else: # Assure 3 channel even when loaded image is grayscale
111         img = img.convert('RGB')
112     return img
113 
114 
115 def list_pictures(directory, ext='jpg|jpeg|bmp|png'):
116     return [join(directory,f) for f in listdir(directory) \
117         if isfile(join(directory,f)) and re.match('([\w]+\.(?:' + ext + '))', f)]
118 
119 
120 
121 class ImageDataGenerator(object):
122     '''
123         Generate minibatches with 
124         realtime data augmentation.
125     '''
126     def __init__(self, 
127             featurewise_center=True, # set input mean to 0 over the dataset
128             samplewise_center=False, # set each sample mean to 0
129             featurewise_std_normalization=True, # divide inputs by std of the dataset
130             samplewise_std_normalization=False, # divide each input by its std
131 
132             zca_whitening=False, # apply ZCA whitening
133             rotation_range=0., # degrees (0 to 180)
134             width_shift_range=0., # fraction of total width
135             height_shift_range=0., # fraction of total height
136             horizontal_flip=False,
137             vertical_flip=False,
138         ):
139         self.__dict__.update(locals())
140         self.mean = None
141         self.std = None
142         self.principal_components = None
143 
144 
145     def flow(self, X, y, batch_size=32, shuffle=False, seed=None, save_to_dir=None, save_prefix="", save_format="jpeg"):
146         if seed:
147             random.seed(seed)
148 
149         if shuffle:
150             seed = random.randint(1, 10e6)
151             np.random.seed(seed)
152             np.random.shuffle(X)
153             np.random.seed(seed)
154             np.random.shuffle(y)
155 
156         nb_batch = int(math.ceil(float(X.shape[0])/batch_size))
157         for b in range(nb_batch):
158             batch_end = (b+1)*batch_size
159             if batch_end > X.shape[0]:
160                 nb_samples = X.shape[0] - b*batch_size
161             else:
162                 nb_samples = batch_size
163 
164             bX = np.zeros(tuple([nb_samples]+list(X.shape)[1:]))
165             for i in range(nb_samples):
166                 x = X[b*batch_size+i]
167                 x = self.random_transform(x.astype("float32"))
168                 x = self.standardize(x)
169                 bX[i] = x
170 
171             if save_to_dir:
172                 for i in range(nb_samples):
173                     img = array_to_img(bX[i], scale=True)
174                     img.save(save_to_dir + "/" + save_prefix + "_" + str(i) + "." + save_format)
175 
176             yield bX, y[b*batch_size:b*batch_size+nb_samples]
177 
178 
179     def standardize(self, x):
180         if self.featurewise_center:
181             x -= self.mean
182         if self.featurewise_std_normalization:
183             x /= self.std
184 
185         if self.zca_whitening:
186             flatx = np.reshape(x, (x.shape[0]*x.shape[1]*x.shape[2]))
187             whitex = np.dot(flatx, self.principal_components)
188             x = np.reshape(whitex, (x.shape[0], x.shape[1], x.shape[2]))
189 
190         if self.samplewise_center:
191             x -= np.mean(x)
192         if self.samplewise_std_normalization:
193             x /= np.std(x)
194 
195         return x
196 
197 
198     def random_transform(self, x):
199         if self.rotation_range:
200             x = random_rotation(x, self.rotation_range)
201         if self.width_shift_range or self.height_shift_range:
202             x = random_shift(x, self.width_shift_range, self.height_shift_range)
203         if self.horizontal_flip:
204             if random.random() < 0.5:
205                 x = horizontal_flip(x)
206         if self.vertical_flip:
207             if random.random() < 0.5:
208                 x = vertical_flip(x)
209 
210         # TODO:
211         # zoom
212         # barrel/fisheye
213         # shearing
214         # channel shifting
215         return x
216 
217 
218     def fit(self, X, 
219             augment=False, # fit on randomly augmented samples
220             rounds=1, # if augment, how many augmentation passes over the data do we use
221             seed=None
222         ):
223         '''
224             Required for featurewise_center, featurewise_std_normalization and zca_whitening.
225         '''
226         X = np.copy(X)
227         
228         if augment:
229             aX = np.zeros(tuple([rounds*X.shape[0]]+list(X.shape)[1:]))
230             for r in range(rounds):
231                 for i in range(X.shape[0]):
232                     img = array_to_img(X[i])
233                     img = self.random_transform(img)
234                     aX[i+r*X.shape[0]] = img_to_array(img)
235             X = aX
236 
237         if self.featurewise_center:
238             self.mean = np.mean(X, axis=0)
239             X -= self.mean
240         if self.featurewise_std_normalization:
241             self.std = np.std(X, axis=0)
242             X /= self.std
243 
244         if self.zca_whitening:
245             flatX = np.reshape(X, (X.shape[0], X.shape[1]*X.shape[2]*X.shape[3]))
246             fudge = 10e-6
247             sigma = np.dot(flatX.T, flatX) / flatX.shape[1]
248             U, S, V = linalg.svd(sigma)
249             self.principal_components = np.dot(np.dot(U, np.diag(1. / np.sqrt(S + fudge))), U.T)
250 
251 
252
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/keras/preprocessing/image.py b/keras/preprocessing/image.py
--- a/keras/preprocessing/image.py
+++ b/keras/preprocessing/image.py
@@ -104,7 +104,7 @@
 
 def load_img(path, grayscale=False):
     from PIL import Image
-    img = Image.open(open(path))
+    img = Image.open(path)
     if grayscale:
         img = img.convert('L')
     else: # Assure 3 channel even when loaded image is grayscale

{"golden_diff": "diff --git a/keras/preprocessing/image.py b/keras/preprocessing/image.py\n--- a/keras/preprocessing/image.py\n+++ b/keras/preprocessing/image.py\n@@ -104,7 +104,7 @@\n \n def load_img(path, grayscale=False):\n     from PIL import Image\n-    img = Image.open(open(path))\n+    img = Image.open(path)\n     if grayscale:\n         img = img.convert('L')\n     else: # Assure 3 channel even when loaded image is grayscale\n", "issue": "Python 3 compatibility problem with Image loading\nLoading an Image using the `load_img` results in an error.\n\n```\nTraceback (most recent call last):\n  File \"keras/autoencoder.py\", line 45, in <module>\n    X_train, Y_train, X_test, Y_test, nb_classes = io.load_images(join(DATA_DIR, 'dataset0'))\n  File \"/home/jnphilipp/Documents/cnn/hieroglyphs/keras/utils/io.py\", line 27, in load_images\n    X_train.append(img_to_array(load_img(picture, True)))\n  File \"/home/jnphilipp/.local/lib/python3.4/site-packages/Keras-0.1.2-py3.4.egg/keras/preprocessing/image.py\", line 107, in load_img\n  File \"/home/jnphilipp/.local/lib/python3.4/site-packages/PIL/Image.py\", line 2330, in open\n    % (filename if filename else fp))\nOSError: cannot identify image file <_io.TextIOWrapper name='/home/jnphilipp/Documents/cnn/hieroglyphs/data/dataset0/train/P1_train0.png' mode='r' encoding='ISO-8859-1'>\n```\n\n", "before_files": [{"content": "from __future__ import absolute_import\n\nimport numpy as np\nimport re\nfrom scipy import ndimage\nfrom scipy import linalg\n\nfrom os import listdir\nfrom os.path import isfile, join\nimport random, math\nfrom six.moves import range\n\n'''\n    Fairly basic set of tools for realtime data augmentation on image data.\n    Can easily be extended to include new transforms, new preprocessing methods, etc...\n'''\n\ndef random_rotation(x, rg, fill_mode=\"nearest\", cval=0.):\n    angle = random.uniform(-rg, rg)\n    x = ndimage.interpolation.rotate(x, angle, axes=(1,2), reshape=False, mode=fill_mode, cval=cval)\n    return x\n\ndef random_shift(x, wrg, hrg, fill_mode=\"nearest\", cval=0.):\n    crop_left_pixels = 0\n    crop_right_pixels = 0\n    crop_top_pixels = 0\n    crop_bottom_pixels = 0\n\n    original_w = x.shape[1]\n    original_h = x.shape[2]\n\n    if wrg:\n        crop = random.uniform(0., wrg)\n        split = random.uniform(0, 1)\n        crop_left_pixels = int(split*crop*x.shape[1])\n        crop_right_pixels = int((1-split)*crop*x.shape[1])\n\n    if hrg:\n        crop = random.uniform(0., hrg)\n        split = random.uniform(0, 1)\n        crop_top_pixels = int(split*crop*x.shape[2])\n        crop_bottom_pixels = int((1-split)*crop*x.shape[2])\n\n    x = ndimage.interpolation.shift(x, (0, crop_left_pixels, crop_top_pixels), mode=fill_mode, cval=cval)\n    return x\n\ndef horizontal_flip(x):\n    for i in range(x.shape[0]):\n        x[i] = np.fliplr(x[i])\n    return x\n\ndef vertical_flip(x):\n    for i in range(x.shape[0]):\n        x[i] = np.flipud(x[i])\n    return x\n\n\ndef random_barrel_transform(x, intensity):\n    # TODO\n    pass\n\ndef random_shear(x, intensity):\n    # TODO\n    pass\n\ndef random_channel_shift(x, rg):\n    # TODO\n    pass\n\ndef random_zoom(x, rg, fill_mode=\"nearest\", cval=0.):\n    zoom_w = random.uniform(1.-rg, 1.)\n    zoom_h = random.uniform(1.-rg, 1.)\n    x = ndimage.interpolation.zoom(x, zoom=(1., zoom_w, zoom_h), mode=fill_mode, cval=cval)\n    return x # shape of result will be different from shape of input!\n\n\n\n\ndef array_to_img(x, scale=True):\n    from PIL import Image\n    x = x.transpose(1, 2, 0) \n    if scale:\n        x += max(-np.min(x), 0)\n        x /= np.max(x)\n        x *= 255\n    if x.shape[2] == 3:\n        # RGB\n        return Image.fromarray(x.astype(\"uint8\"), \"RGB\")\n    else:\n        # grayscale\n        return Image.fromarray(x[:,:,0].astype(\"uint8\"), \"L\")\n\n\ndef img_to_array(img):\n    x = np.asarray(img, dtype='float32')\n    if len(x.shape)==3:\n        # RGB: height, width, channel -> channel, height, width\n        x = x.transpose(2, 0, 1)\n    else:\n        # grayscale: height, width -> channel, height, width\n        x = x.reshape((1, x.shape[0], x.shape[1]))\n    return x\n\n\ndef load_img(path, grayscale=False):\n    from PIL import Image\n    img = Image.open(open(path))\n    if grayscale:\n        img = img.convert('L')\n    else: # Assure 3 channel even when loaded image is grayscale\n        img = img.convert('RGB')\n    return img\n\n\ndef list_pictures(directory, ext='jpg|jpeg|bmp|png'):\n    return [join(directory,f) for f in listdir(directory) \\\n        if isfile(join(directory,f)) and re.match('([\\w]+\\.(?:' + ext + '))', f)]\n\n\n\nclass ImageDataGenerator(object):\n    '''\n        Generate minibatches with \n        realtime data augmentation.\n    '''\n    def __init__(self, \n            featurewise_center=True, # set input mean to 0 over the dataset\n            samplewise_center=False, # set each sample mean to 0\n            featurewise_std_normalization=True, # divide inputs by std of the dataset\n            samplewise_std_normalization=False, # divide each input by its std\n\n            zca_whitening=False, # apply ZCA whitening\n            rotation_range=0., # degrees (0 to 180)\n            width_shift_range=0., # fraction of total width\n            height_shift_range=0., # fraction of total height\n            horizontal_flip=False,\n            vertical_flip=False,\n        ):\n        self.__dict__.update(locals())\n        self.mean = None\n        self.std = None\n        self.principal_components = None\n\n\n    def flow(self, X, y, batch_size=32, shuffle=False, seed=None, save_to_dir=None, save_prefix=\"\", save_format=\"jpeg\"):\n        if seed:\n            random.seed(seed)\n\n        if shuffle:\n            seed = random.randint(1, 10e6)\n            np.random.seed(seed)\n            np.random.shuffle(X)\n            np.random.seed(seed)\n            np.random.shuffle(y)\n\n        nb_batch = int(math.ceil(float(X.shape[0])/batch_size))\n        for b in range(nb_batch):\n            batch_end = (b+1)*batch_size\n            if batch_end > X.shape[0]:\n                nb_samples = X.shape[0] - b*batch_size\n            else:\n                nb_samples = batch_size\n\n            bX = np.zeros(tuple([nb_samples]+list(X.shape)[1:]))\n            for i in range(nb_samples):\n                x = X[b*batch_size+i]\n                x = self.random_transform(x.astype(\"float32\"))\n                x = self.standardize(x)\n                bX[i] = x\n\n            if save_to_dir:\n                for i in range(nb_samples):\n                    img = array_to_img(bX[i], scale=True)\n                    img.save(save_to_dir + \"/\" + save_prefix + \"_\" + str(i) + \".\" + save_format)\n\n            yield bX, y[b*batch_size:b*batch_size+nb_samples]\n\n\n    def standardize(self, x):\n        if self.featurewise_center:\n            x -= self.mean\n        if self.featurewise_std_normalization:\n            x /= self.std\n\n        if self.zca_whitening:\n            flatx = np.reshape(x, (x.shape[0]*x.shape[1]*x.shape[2]))\n            whitex = np.dot(flatx, self.principal_components)\n            x = np.reshape(whitex, (x.shape[0], x.shape[1], x.shape[2]))\n\n        if self.samplewise_center:\n            x -= np.mean(x)\n        if self.samplewise_std_normalization:\n            x /= np.std(x)\n\n        return x\n\n\n    def random_transform(self, x):\n        if self.rotation_range:\n            x = random_rotation(x, self.rotation_range)\n        if self.width_shift_range or self.height_shift_range:\n            x = random_shift(x, self.width_shift_range, self.height_shift_range)\n        if self.horizontal_flip:\n            if random.random() < 0.5:\n                x = horizontal_flip(x)\n        if self.vertical_flip:\n            if random.random() < 0.5:\n                x = vertical_flip(x)\n\n        # TODO:\n        # zoom\n        # barrel/fisheye\n        # shearing\n        # channel shifting\n        return x\n\n\n    def fit(self, X, \n            augment=False, # fit on randomly augmented samples\n            rounds=1, # if augment, how many augmentation passes over the data do we use\n            seed=None\n        ):\n        '''\n            Required for featurewise_center, featurewise_std_normalization and zca_whitening.\n        '''\n        X = np.copy(X)\n        \n        if augment:\n            aX = np.zeros(tuple([rounds*X.shape[0]]+list(X.shape)[1:]))\n            for r in range(rounds):\n                for i in range(X.shape[0]):\n                    img = array_to_img(X[i])\n                    img = self.random_transform(img)\n                    aX[i+r*X.shape[0]] = img_to_array(img)\n            X = aX\n\n        if self.featurewise_center:\n            self.mean = np.mean(X, axis=0)\n            X -= self.mean\n        if self.featurewise_std_normalization:\n            self.std = np.std(X, axis=0)\n            X /= self.std\n\n        if self.zca_whitening:\n            flatX = np.reshape(X, (X.shape[0], X.shape[1]*X.shape[2]*X.shape[3]))\n            fudge = 10e-6\n            sigma = np.dot(flatX.T, flatX) / flatX.shape[1]\n            U, S, V = linalg.svd(sigma)\n            self.principal_components = np.dot(np.dot(U, np.diag(1. / np.sqrt(S + fudge))), U.T)\n\n\n", "path": "keras/preprocessing/image.py"}], "after_files": [{"content": "from __future__ import absolute_import\n\nimport numpy as np\nimport re\nfrom scipy import ndimage\nfrom scipy import linalg\n\nfrom os import listdir\nfrom os.path import isfile, join\nimport random, math\nfrom six.moves import range\n\n'''\n    Fairly basic set of tools for realtime data augmentation on image data.\n    Can easily be extended to include new transforms, new preprocessing methods, etc...\n'''\n\ndef random_rotation(x, rg, fill_mode=\"nearest\", cval=0.):\n    angle = random.uniform(-rg, rg)\n    x = ndimage.interpolation.rotate(x, angle, axes=(1,2), reshape=False, mode=fill_mode, cval=cval)\n    return x\n\ndef random_shift(x, wrg, hrg, fill_mode=\"nearest\", cval=0.):\n    crop_left_pixels = 0\n    crop_right_pixels = 0\n    crop_top_pixels = 0\n    crop_bottom_pixels = 0\n\n    original_w = x.shape[1]\n    original_h = x.shape[2]\n\n    if wrg:\n        crop = random.uniform(0., wrg)\n        split = random.uniform(0, 1)\n        crop_left_pixels = int(split*crop*x.shape[1])\n        crop_right_pixels = int((1-split)*crop*x.shape[1])\n\n    if hrg:\n        crop = random.uniform(0., hrg)\n        split = random.uniform(0, 1)\n        crop_top_pixels = int(split*crop*x.shape[2])\n        crop_bottom_pixels = int((1-split)*crop*x.shape[2])\n\n    x = ndimage.interpolation.shift(x, (0, crop_left_pixels, crop_top_pixels), mode=fill_mode, cval=cval)\n    return x\n\ndef horizontal_flip(x):\n    for i in range(x.shape[0]):\n        x[i] = np.fliplr(x[i])\n    return x\n\ndef vertical_flip(x):\n    for i in range(x.shape[0]):\n        x[i] = np.flipud(x[i])\n    return x\n\n\ndef random_barrel_transform(x, intensity):\n    # TODO\n    pass\n\ndef random_shear(x, intensity):\n    # TODO\n    pass\n\ndef random_channel_shift(x, rg):\n    # TODO\n    pass\n\ndef random_zoom(x, rg, fill_mode=\"nearest\", cval=0.):\n    zoom_w = random.uniform(1.-rg, 1.)\n    zoom_h = random.uniform(1.-rg, 1.)\n    x = ndimage.interpolation.zoom(x, zoom=(1., zoom_w, zoom_h), mode=fill_mode, cval=cval)\n    return x # shape of result will be different from shape of input!\n\n\n\n\ndef array_to_img(x, scale=True):\n    from PIL import Image\n    x = x.transpose(1, 2, 0) \n    if scale:\n        x += max(-np.min(x), 0)\n        x /= np.max(x)\n        x *= 255\n    if x.shape[2] == 3:\n        # RGB\n        return Image.fromarray(x.astype(\"uint8\"), \"RGB\")\n    else:\n        # grayscale\n        return Image.fromarray(x[:,:,0].astype(\"uint8\"), \"L\")\n\n\ndef img_to_array(img):\n    x = np.asarray(img, dtype='float32')\n    if len(x.shape)==3:\n        # RGB: height, width, channel -> channel, height, width\n        x = x.transpose(2, 0, 1)\n    else:\n        # grayscale: height, width -> channel, height, width\n        x = x.reshape((1, x.shape[0], x.shape[1]))\n    return x\n\n\ndef load_img(path, grayscale=False):\n    from PIL import Image\n    img = Image.open(path)\n    if grayscale:\n        img = img.convert('L')\n    else: # Assure 3 channel even when loaded image is grayscale\n        img = img.convert('RGB')\n    return img\n\n\ndef list_pictures(directory, ext='jpg|jpeg|bmp|png'):\n    return [join(directory,f) for f in listdir(directory) \\\n        if isfile(join(directory,f)) and re.match('([\\w]+\\.(?:' + ext + '))', f)]\n\n\n\nclass ImageDataGenerator(object):\n    '''\n        Generate minibatches with \n        realtime data augmentation.\n    '''\n    def __init__(self, \n            featurewise_center=True, # set input mean to 0 over the dataset\n            samplewise_center=False, # set each sample mean to 0\n            featurewise_std_normalization=True, # divide inputs by std of the dataset\n            samplewise_std_normalization=False, # divide each input by its std\n\n            zca_whitening=False, # apply ZCA whitening\n            rotation_range=0., # degrees (0 to 180)\n            width_shift_range=0., # fraction of total width\n            height_shift_range=0., # fraction of total height\n            horizontal_flip=False,\n            vertical_flip=False,\n        ):\n        self.__dict__.update(locals())\n        self.mean = None\n        self.std = None\n        self.principal_components = None\n\n\n    def flow(self, X, y, batch_size=32, shuffle=False, seed=None, save_to_dir=None, save_prefix=\"\", save_format=\"jpeg\"):\n        if seed:\n            random.seed(seed)\n\n        if shuffle:\n            seed = random.randint(1, 10e6)\n            np.random.seed(seed)\n            np.random.shuffle(X)\n            np.random.seed(seed)\n            np.random.shuffle(y)\n\n        nb_batch = int(math.ceil(float(X.shape[0])/batch_size))\n        for b in range(nb_batch):\n            batch_end = (b+1)*batch_size\n            if batch_end > X.shape[0]:\n                nb_samples = X.shape[0] - b*batch_size\n            else:\n                nb_samples = batch_size\n\n            bX = np.zeros(tuple([nb_samples]+list(X.shape)[1:]))\n            for i in range(nb_samples):\n                x = X[b*batch_size+i]\n                x = self.random_transform(x.astype(\"float32\"))\n                x = self.standardize(x)\n                bX[i] = x\n\n            if save_to_dir:\n                for i in range(nb_samples):\n                    img = array_to_img(bX[i], scale=True)\n                    img.save(save_to_dir + \"/\" + save_prefix + \"_\" + str(i) + \".\" + save_format)\n\n            yield bX, y[b*batch_size:b*batch_size+nb_samples]\n\n\n    def standardize(self, x):\n        if self.featurewise_center:\n            x -= self.mean\n        if self.featurewise_std_normalization:\n            x /= self.std\n\n        if self.zca_whitening:\n            flatx = np.reshape(x, (x.shape[0]*x.shape[1]*x.shape[2]))\n            whitex = np.dot(flatx, self.principal_components)\n            x = np.reshape(whitex, (x.shape[0], x.shape[1], x.shape[2]))\n\n        if self.samplewise_center:\n            x -= np.mean(x)\n        if self.samplewise_std_normalization:\n            x /= np.std(x)\n\n        return x\n\n\n    def random_transform(self, x):\n        if self.rotation_range:\n            x = random_rotation(x, self.rotation_range)\n        if self.width_shift_range or self.height_shift_range:\n            x = random_shift(x, self.width_shift_range, self.height_shift_range)\n        if self.horizontal_flip:\n            if random.random() < 0.5:\n                x = horizontal_flip(x)\n        if self.vertical_flip:\n            if random.random() < 0.5:\n                x = vertical_flip(x)\n\n        # TODO:\n        # zoom\n        # barrel/fisheye\n        # shearing\n        # channel shifting\n        return x\n\n\n    def fit(self, X, \n            augment=False, # fit on randomly augmented samples\n            rounds=1, # if augment, how many augmentation passes over the data do we use\n            seed=None\n        ):\n        '''\n            Required for featurewise_center, featurewise_std_normalization and zca_whitening.\n        '''\n        X = np.copy(X)\n        \n        if augment:\n            aX = np.zeros(tuple([rounds*X.shape[0]]+list(X.shape)[1:]))\n            for r in range(rounds):\n                for i in range(X.shape[0]):\n                    img = array_to_img(X[i])\n                    img = self.random_transform(img)\n                    aX[i+r*X.shape[0]] = img_to_array(img)\n            X = aX\n\n        if self.featurewise_center:\n            self.mean = np.mean(X, axis=0)\n            X -= self.mean\n        if self.featurewise_std_normalization:\n            self.std = np.std(X, axis=0)\n            X /= self.std\n\n        if self.zca_whitening:\n            flatX = np.reshape(X, (X.shape[0], X.shape[1]*X.shape[2]*X.shape[3]))\n            fudge = 10e-6\n            sigma = np.dot(flatX.T, flatX) / flatX.shape[1]\n            U, S, V = linalg.svd(sigma)\n            self.principal_components = np.dot(np.dot(U, np.diag(1. / np.sqrt(S + fudge))), U.T)\n\n\n", "path": "keras/preprocessing/image.py"}]}