Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PIL image to array (numpy array to array) - Python

Tags:

I have a .jpg image that I would like to convert to Python array, because I implemented treatment routines handling plain Python arrays.

It seems that PIL images support conversion to numpy array, and according to the documentation I have written this:

from PIL import Image im = Image.open("D:\Prototype\Bikesgray.jpg") im.show()  print(list(np.asarray(im))) 

This is returning a list of numpy arrays. Also, I tried with

list([list(x) for x in np.asarray(im)]) 

which is returning nothing at all since it is failing.

How can I convert from PIL to array, or simply from numpy array to Python array?

like image 994
kiriloff Avatar asked Nov 25 '12 10:11

kiriloff


People also ask

Can an image could be converted into a NumPy array?

Using OpenCV Library imread() function is used to load the image and It also reads the given image (PIL image) in the NumPy array format. Then we need to convert the image color from BGR to RGB. imwrite() is used to save the image in the file.

Does pillow use NumPy?

In this chapter, we use numpy to store and manipulate image data using python imaging library – “pillow”. Note − This works only if you have PIP installed and updated.

Why do we convert image to NumPy array?

Converting an image to an array is an important task to train a machine learning model based on the features of an image. We mainly use the NumPy library in Python to work with arrays so we can also use it to convert images to an array. Other than NumPy, we can also use the Keras library in Python for the same task.


1 Answers

I highly recommend you use the tobytes function of the Image object. After some timing checks this is much more efficient.

def jpg_image_to_array(image_path):   """   Loads JPEG image into 3D Numpy array of shape    (width, height, channels)   """   with Image.open(image_path) as image:              im_arr = np.fromstring(image.tobytes(), dtype=np.uint8)     im_arr = im_arr.reshape((image.size[1], image.size[0], 3))                                      return im_arr 

The timings I ran on my laptop show

In [76]: %timeit np.fromstring(im.tobytes(), dtype=np.uint8) 1000 loops, best of 3: 230 µs per loop  In [77]: %timeit np.array(im.getdata(), dtype=np.uint8) 10 loops, best of 3: 114 ms per loop 

```

like image 178
awnihannun Avatar answered Sep 28 '22 12:09

awnihannun