Python pil image to numpy array

How To Convert PIL Images to Numpy Array

pil image to numpy array

This article will discuss the PIL module and various ways to convert an image to a Numpy array. Before that, let’s see what the Python PIL and Numpy module offers.

PIL (Python Image Library) is an image processing package created for Python. It provides various classes and methods that aid in the creation, editing, and exportation of image documents. Unfortunately, support for the PIL module was discontinued in 2011. However, the Pillow project, which had similar objectives, forked the PIL module. Eventually, the Pillow module replaced PIL and became the default image processing tool for Python developers.

Читайте также:  Php flat visual chat

Now that we have a brief idea about PIL let’s see what the Numpy module is about.

Numpy is the go-to module for scientific computations in Python. Numpy introduces an array object called “ndarray”. They are faster and more potent than traditional Python lists. Data Scientists make use of this module due to its efficiency and proper resource management.

Installing the Modules

PIL / Pillow

PIL is not part of the Python Standard Library. Use the following command to install PIL via PIP manually.

PIP Command for PIL/Pillow (MacOs/Linux & Windows) $ pip install Pillow 

NumPy

Numpy is not part of the Python Standard Library. Install using the following PIP command.

PIP Command for Numpy (MacOs/Linux & Windows) $ pip install numpy

How are PIL Images Stored? What are its Formats?

The save() function allows us to store images into multiple supported image formats.

Let’s look at the fully supported formats by the Pillow module.

Different Ways to a Convert PIL Image to a Numpy Array

Now that we have a brief idea about the Pillow module and the Numpy module let’s see various ways to convert a PIL image to a Numpy array.

Convert PIL Image to Numpy Array Using numpy.asarray() function

To convert a PIL image object to a numpy array, we can use numpy.asarray() .

Using numpy.asarray() , we can initialize array types. Therefore, passing a PIL image object to .asarray() will convert it into a ndarray.

import numpy as np from PIL import Image myImage = Image.open("/content/companylogo.jpg") myImageArr = np.asarray(myImage) print(myImageArr.shape)

Output

Convert PIL Image to Numpy array Using numpy.array() Function

Similarly, we can use the numpy.asarray() to convert a PIL image to a numpy array object.

numpy.array() function allows us to create and initialize numpy array objects. Using the function, we are converting the PIL image to a 3D ndarray. Let’s look at the following program.

import numpy as np from PIL import Image myImage = Image.open("/content/companylogo.jpg") myImageArr = np.array(myImage) print(myImageArr.shape)

Output

In the above programs, we have transformed the image companylogo.png to a 3D Numpy ndarray myImageArr . Finally, we have displayed the array shapes. Note that both functions .array() and .asarray() produce similar outputs.

How To Convert a 2D Matrix to an Image in Python

Using the Numpy ndarray and the Pillow module, we can transform a 2D matrix from Numpy to an Image file. Let’s look at the following implementation.

from PIL import Image import numpy as np # Creating an matrix of size 50x50 with integer values myArray = np.random.randint(300, size=(50,50), dtype=np.uint8) resImage = Image.fromarray(arr) # Exporting the image in png format resImage.save("image2Darray.png")

Output

image2Darray.png convert numpy array to pil image

How to Convert an RGB Image to a Numpy Array

Python modules like matplotlib and openCV natively use Numpy arrays. Therefore, with the help of OpenCV , we can load an RGB Image as a Numpy array.

import cv2 imageArray = cv2.imread("RGBImage.tiff",mode='RGB') print(type(imageArray))

Output

How to Convert a 2D Numpy Array with Grayscale Values to PIL Object

Using the .linspace function, we can create a gradient between 0 and 1. The fromarray() function allows us to convert it into PIL image format.

Let’s look at the following implementation.

import numpy as np from PIL import Image myArray = np.linspace(0,1,256*256) array2D = np.reshape(myArray,(256,256)) # Creates PIL image imgGray = Image.fromarray( array2D , 'L') imgGray.save("grayscale.png")

Output

grayscale image

How To Convert a Base64 Image to Numpy Array

For example, let’s say you’re receiving a base64 encoded image from HTTP. How do we convert to a Numpy Array?

Let’s look at the following example:

import torch import numpy as np from PIL import Image import base64 base64_decoded = base64.b64decode(test_image_base64_encoded) with open("sample.jpg", "wb") as sample: sample.write(base64_decoded) image = Image.open("sample.jpg") imageArray = np.array(image)

Explanation

First off, we are decoding the base64 image. Then, we create a JPG file and write the decoded image into the file. Finally, we open the image and convert it into a NumPy array.

FAQs

Numpy provides a function that aids the creation of a numpy array object. Use numpy.array() or numpy.asarray()

The PIL modules provide a function .fromarray() that takes an array as a parameter. This allows us to convert an array object to a PIL image object.

Conclusion

In this article, we have reviewed a powerful image processing tool in Python called PIL/Pillow. Various techniques to convert image objects to a Numpy array and vice versa have been taught. We have learned the multiple image formats the PIL module allows us to work with.

Источник

How to Convert PIL Image to Numpy Array in Python

To convert an Image to a Numpy array, you can use the “numpy.array()” method and get an image data array.

PIL (Python Image Library) is an image processing package created for Python. It provides various classes and methods that aid in creating, editing, and exporting image documents.

You can install the pillow library using the below command:

Example

edit image using numpy array

Let’s convert this Image into a numpy array.

import numpy as np from PIL import Image img_data = Image.open('forest.jpg') img_arr = np.array(img_data) print(img_arr)
[[[178 204 231] [173 199 226] [174 200 227] . [153 188 218] [153 188 218] [154 189 219]] [[174 200 227] [171 197 224] [175 201 228] . [151 186 216] [149 184 214] [147 182 212]] [[171 197 224] [170 196 223] [175 201 228] . [150 185 215] [147 182 212] [144 179 209]] . [[130 94 46] [142 105 53] [182 143 86] . [ 56 55 51] [ 52 50 53] [ 44 41 48]] [[137 96 66] [126 83 48] [154 111 66] . [ 43 42 37] [ 38 36 39] [ 37 34 43]] [[ 98 56 32] [110 67 35] [130 87 44] . [ 40 39 34] [ 37 35 40] [ 44 41 52]]]

You can see in the output that we get the numpy array of image data.

We used the Image.open() method and np.array() method to convert PIL Image into Numpy array.

The shape of the img_arr is the following.

import numpy as np from PIL import Image img_data = Image.open('forest.jpg') img_arr = np.array(img_data) print(img_arr.shape)

How to Convert Numpy Array to PIL Image in Python

To convert a Numpy Array to PIL Image in Python, use the “Image.fromarray()” method. To change, modify or edit the Image using numpy, convert it into a numpy array, and then perform the mathematical operation to edit the array and then convert it back into the Image using Image.array() method.

Example

import numpy as np from PIL import Image img_data = Image.open('forest.jpg') img_arr = np.array(img_data) print(img_arr.shape) img_arr = img_arr - 180 new_img = Image.fromarray(img_arr) new_img.save("altered_forest.png")

Convert PIL Image to Numpy Array in Python

In this example, we have converted a PIL Image to a Numpy array using the np array() method and then modified its pixel and converted the array to the PIL image using the fromarray() method.

How to Convert a 2D Numpy Array with Grayscale Values to PIL Object

Using the .linspace() method, we can create a gradient between 0 and 1. The fromarray() function converts it into PIL image format.

Example

import numpy as np from PIL import Image main_array = np.linspace(0, 1, 256*256) array2D = np.reshape(main_array, (256, 256)) # Creates PIL image imgGray = Image.fromarray(array2D, 'L') imgGray.save("grayscale.png") 

How to Convert a 2D Numpy Array with Grayscale Values to PIL Object

How to Convert a Base64 Image to Numpy Array

To convert a Base64 image to a numpy array, you can follow these steps:

  1. Decode the Base64 string to get the binary data of the image.
  2. Convert the binary data to a PIL image.
  3. Convert the PIL image to a numpy array.
import base64 import io from PIL import Image import numpy as np # Suppose base64_image is your Base64 string # base64_image = ". " # Step 1: Decode the Base64 string img_data = base64.b64decode(base64_image) # Step 2: Convert the binary data to a PIL image image = Image.open(io.BytesIO(img_data)) # Step 3: Convert the PIL image to a numpy array image_array = np.array(image) 

Источник

Convert PIL Image to NumPy Array

Convert PIL Image to NumPy Array

  1. Convert PIL Image to NumPy Array With the numpy.array() Function in Python
  2. Convert PIL Image to NumPy Array With the numpy.asarray() Function in Python

This tutorial will discuss the methods to convert a PIL image to a 3-dimensional NumPy array in Python.

Convert PIL Image to NumPy Array With the numpy.array() Function in Python

PIL is used to perform various operations on images in Python. The Pillow library does not come pre-installed with the Python programming language. So, we have to install it first. The command to install the Pillow library is given below.

If we want to convert an image read by the PIL library to a NumPy array, we can use the numpy.array() function. The numpy.array() function creates and initializes numpy arrays. The numpy.array() function will convert the PIL image to a 3-dimensional array. See the following code example.

import numpy as np from PIL import Image img = Image.open("NASA.jpg") imgArray = np.array(img) print(imgArray.shape) 

In the above code, we converted the PIL image img to a 3-dimensional NumPy array imgArray with the numpy.array() function. We read the image inside the variable img with the Image.open() function in Python. We then converted the img to the NumPy array imgArray with the numpy.array() function in Python. In the end, we printed the shape of the imgArray with the print() function.

Convert PIL Image to NumPy Array With the numpy.asarray() Function in Python

We can also use the numpy.asarray() function to achieve the same goal as the previous example. The numpy.asarray() function also creates and initializes an numpy array. We can convert a PIL image to a numPy array by passing the image to the numpy.asarray() function. See the following code example.

import numpy as np from PIL import Image img = Image.open("NASA.jpg") imgArray = np.asarray(img) print(imgArray.shape) 

In the above code, we converted the PIL image img to the 3-dimensional NumPy array imgArray with the numpy.array() function in Python. We loaded the in the img variable with the Image.open() function in Python. We then converted the img image to the NumPy array imgArray with the numpy.asarray() function in Python. In the end, we printed the shape of the imgArray with the print() function.

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

Источник

Оцените статью