How to use Keras API to Convert images to NumPy array In NumPy
Keras API provides the functions for loading, converting, and saving image data. Keras is possible to run on the top of the TensorFlow framework and hence that is mandatory to have. Deep learning computer vision images require Keras API. To install it type the below command in the terminal
pip install keras
As Keras requires TensorFlow 2.2 or higher. If not there, need to install it. To install it type the below command in the terminal.
pip install tensorflow
Python3
from keras.preprocessing.image import load_img import warnings # load the image via load_img # function img = load_img( 'sample.png' ) # details about the image printed below print ( type (img)) print (img. format ) print (img.mode) print (img.size) |
Output :
<class 'PIL.PngImagePlugin.PngImageFile'> PNG RGB (400, 200)
Using Keras API, convert images to Numpy Array and reverting the image from Numpy Array
Python3
from keras.preprocessing.image import img_to_array from keras.preprocessing.image import array_to_img # details about the image printed below print ( type (img)) print (img. format ) print (img.mode) print (img.size) # convert the given image into numpy array img_numpy_array = img_to_array(img) print ( "Image is converted and NumPy array information :" ) # <class 'numpy.ndarray'> print ( type (img_numpy_array)) # type: float32 print ( "type:" , img_numpy_array.dtype) # shape: (200, 400, 3) print ( "shape:" , img_numpy_array.shape) # convert back to image img_pil_from_numpy_array = array_to_img(img_numpy_array) # <class 'PIL.PngImagePlugin.PngImageFile'> print ( "converting NumPy array into image:" , type (img_pil_from_numpy_array)) |
Output :
<class 'PIL.PngImagePlugin.PngImageFile'> PNG RGB (400, 200) Image is converted and NumPy array information : <class 'numpy.ndarray'> type: float32 shape: (200, 400, 3) converting NumPy array into image: <class 'PIL.Image.Image'>
From the above output, we can check that the source image PIL.Image.Image and destination image types are the same.
How to Convert images to NumPy array?
Images are an easier way to represent the working model. In Machine Learning, Python uses the image data in the format of Height, Width, Channel format. i.e. Images are converted into Numpy Array in Height, Width, Channel format. In this article we will see How to Convert images to NumPy array?
Modules Needed:
- NumPy: By default in higher versions of Python like 3.x onwards, NumPy is available and if not available(in lower versions), one can install by using
pip install numpy
- Pillow: This has to be explicitly installed in later versions too. It is a preferred image manipulation tool. In Python 3, Pillow python library which is nothing but the upgradation of PIL only. It can be installed using
pip install Pillow
Contact Us