# Converts PIL Image to Numpy Array

```python
"""
   Copyright 2011 Shao-Chuan Wang <shaochuan.wang AT gmail.com>

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    THE SOFTWARE.
"""

import numpy
import Image

def PIL2array(img):
    return numpy.array(img.getdata(),
                    numpy.uint8).reshape(img.size[1], img.size[0], 3)

def array2PIL(arr, size):
    mode = 'RGBA'
    arr = arr.reshape(arr.shape[0]*arr.shape[1], arr.shape[2])
    if len(arr[0]) == 3:
        arr = numpy.c_[arr, 255*numpy.ones((len(arr),1), numpy.uint8)]
    return Image.frombuffer(mode, size, arr.tostring(), 'raw', mode, 0, 1)

def main():
    img = loadImage('foo.jpg')
    arr = PIL2array(img)
    img2 = array2PIL(arr, img.size)
    img2.save('out.jpg')

if __name__ == '__main__':
    main()
```

Alternatively, to get a numpy array from an image use:

```python
from PIL import Image
from numpy import array
img = Image.open("input.png")
arr = array(img)
```

And to get an image from a numpy array, use:

```python
img = Image.fromarray(arr)
img.save("output.png")
```

Reference : <http://code.activestate.com/recipes/577591-conversion-of-pil-image-and-numpy-array/>

## [Create Numpy array of images](https://stackoverflow.com/questions/37747021/create-numpy-array-of-images)

```python
# two classes (class1, class2)
# only replace with a directory of yours
# finally .npy files saved in your directory with names train.npy, #test.npy, train_labels.npy, test_labels.npy
import cv2
import glob
import numpy as np
#Train data
train = []
train_labels = []
files = glob.glob ("/data/train/class1/*.png") # your image path
for myFile in files:
    image = cv2.imread (myFile)
    train.append (image)
    train_labels.append([1., 0.])
files = glob.glob ("/data/train/class2/*.png")
for myFile in files:
    image = cv2.imread (myFile)
    train.append (image)
    train_labels.append([0., 1.])
train = np.array(train,dtype='float32') #as mnist
train_labels = np.array(train_labels,dtype='float64') #as mnist
# convert (number of images x height x width x number of channels) to (number of images x (height * width *3)) 
# for example (120 * 40 * 40 * 3)-> (120 * 4800)
train = np.reshape(train,[train.shape[0],train.shape[1]*train.shape[2]*train.shape[3]])

# save numpy array as .npy formats
np.save('train',train)
np.save('train_labels',train_labels)

#Test data
test = []
test_labels = []
files = glob.glob ("/data/test/class1/*.png")
for myFile in files:
    image = cv2.imread (myFile)
    test.append (image)
    test_labels.append([1., 0.]) # class1
files = glob.glob ("/data/test/class2/*.png")
for myFile in files:
    image = cv2.imread (myFile)
    test.append (image)
    test_labels.append([0., 1.]) # class2

test = np.array(test,dtype='float32') #as mnist example
test_labels = np.array(test_labels,dtype='float64') #as mnist
test = np.reshape(test,[test.shape[0],test.shape[1]*test.shape[2]*test.shape[3]])

# save numpy array as .npy formats
np.save('test',test) # saves test.npy
np.save('test_labels',test_labels)
```
