Sometimes, we want to convert a PIL Image into a NumPy array with Python.
In this article, we’ll look at how to convert a PIL Image into a NumPy array with Python.
How to convert a PIL Image into a NumPy array with Python?
To convert a PIL Image into a NumPy array with Python, we call the Image.open
method from PIL
.
Next, we call convert
with 'L'
to convert that to an image object that we can pass into numpy.array
.
Then we call numpy.array
with the returned image object to return a NumPy array.
For instance, we write:
import numpy
from PIL import Image
img = Image.open("art.png").convert("L")
imgarr = numpy.array(img)
print(imgarr)
to call Image.open
with the path to the image file.
Then we call convert
with 'L'
to return image object that we pass into numpy.array
to generate the array and return it,
Therefore, imgarr
is something like:
[[29 29 29 ... 29 29 29]
[29 29 29 ... 29 29 29]
[29 29 29 ... 29 29 29]
...
[29 29 29 ... 29 29 29]
[29 29 29 ... 29 29 29]
[29 29 29 ... 29 29 29]]
Conclusion
To convert a PIL Image into a NumPy array with Python, we call the Image.open
method from PIL
.
Next, we call convert
with 'L'
to convert that to an image object that we can pass into numpy.array
.
Then we call numpy.array
with the returned image object to return a NumPy array.