How to use NumPy module to Convert images to NumPy array In NumPy
Numpy module in itself provides various methods to do the same. These methods are –
Example 1:Using asarray() function
asarray() function is used to convert PIL images into NumPy arrays. This function converts the input to an array
Python3
# Import the necessary libraries from PIL import Image from numpy import asarray # load the image and convert into # numpy array img = Image. open ( 'Sample.png' ) # asarray() class is used to convert # PIL images into NumPy arrays numpydata = asarray(img) # <class 'numpy.ndarray'> print ( type (numpydata)) # shape print (numpydata.shape) |
Output :
<class 'numpy.ndarray'> (200, 400, 3)
Example 2: Using numpy.array() function
By using numpy.array() function which takes an image as the argument and converts to NumPy array
Python3
from PIL import Image import numpy img = Image. open ( "Sample.png" ) np_img = numpy.array(img) print (np_img.shape) |
Output :
(200, 400, 3)
In order to get the value of each pixel of the NumPy array image, we need to print the retrieved data that got either from asarray() function or array() function.
Python3
# Import the necessary libraries from PIL import Image from numpy import asarray # load the image and convert into # numpy array img = Image. open ( 'Sample.png' ) numpydata = asarray(img) # data print (numpydata) |
Output :
[[[111 60 0] [116 65 0] [122 69 0] ... [ 97 47 0] [ 99 47 0] [100 49 0]] [[111 61 0] [118 65 0] [122 69 0] ... [ 97 47 0] [ 99 48 0] [100 49 0]] [[118 65 0] [122 69 0] [126 73 3] ... [ 98 48 0] [100 49 0] [100 49 0]] ... [[ 96 44 7] [ 95 43 6] [ 93 41 4] ... [225 80 3] [228 80 0] [229 78 0]] [[ 93 40 6] [ 90 37 5] [ 85 32 0] ... [226 81 4] [231 80 1] [232 79 1]] [[ 89 36 4] [ 84 31 0] [ 79 26 0] ... [228 81 4] [232 81 4] [233 80 2]]]
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