How to Convert a NumPy Array to PIL Image in Python

  1. Method 1: Using Image.fromarray()
  2. Method 2: Converting Grayscale Images
  3. Method 3: Customizing Image Properties
  4. Conclusion
  5. FAQ
How to Convert a NumPy Array to PIL Image in Python

Converting a NumPy array to a PIL image is a common task in image processing and computer vision. If you’re working on a project that involves manipulating images, you may find yourself needing to convert arrays into images for visualization or further processing. The Python Imaging Library (PIL), now maintained under the Pillow project, provides a simple and effective way to achieve this. In this tutorial, we will explore how to use the Image.fromarray() function from the PIL package to convert a NumPy array into a PIL image.

Understanding this conversion process can significantly enhance your image processing skills. Whether you’re working on a machine learning project or a simple image manipulation task, mastering this conversion can streamline your workflow. So, let’s dive into the step-by-step methods to convert a NumPy array into a PIL image.

Method 1: Using Image.fromarray()

The most straightforward method to convert a NumPy array to a PIL image is by using the Image.fromarray() function. This method is efficient and works seamlessly for most use cases. Here’s how you can implement it:

import numpy as np
from PIL import Image

# Create a NumPy array
array = np.random.rand(100, 100, 3) * 255
array = array.astype(np.uint8)

# Convert the NumPy array to a PIL image
image = Image.fromarray(array)

# Display the image
image.show()

In this code snippet, we first create a random NumPy array representing a 100x100 RGB image. The values are scaled to the range of 0-255 and converted to uint8, which is the expected data type for image processing. The Image.fromarray() function then takes this array and converts it into a PIL image object. Finally, we use the show() method to display the resulting image.

Output:

Convert a Numpy array to a PIL image using Image.fromarray

This method is particularly useful when you need to visualize data that has been processed or generated programmatically. The flexibility of NumPy arrays allows for a wide range of image manipulations before the conversion, making this approach a popular choice among developers.

Method 2: Converting Grayscale Images

Sometimes, you may be working with grayscale images represented as 2D NumPy arrays. The conversion process is slightly different but still straightforward. Here’s how to handle grayscale images:

import numpy as np
from PIL import Image

# Create a 2D NumPy array for a grayscale image
gray_array = np.random.rand(100, 100) * 255
gray_array = gray_array.astype(np.uint8)

# Convert the 2D NumPy array to a PIL image
gray_image = Image.fromarray(gray_array, mode='L')

# Display the grayscale image
gray_image.show()

In this example, we generate a 2D NumPy array representing a grayscale image. Similar to the RGB example, we scale the values and convert them to uint8. However, when using Image.fromarray(), we specify the mode as ‘L’ to indicate that the image is in grayscale. This ensures that the image is correctly interpreted and displayed.

Output:

Convert a Grayscaled Numpy array to a PIL image using Image.fromarray

This method is particularly useful for applications in fields like medical imaging or any scenario where grayscale representation is needed. By understanding how to handle both RGB and grayscale images, you can effectively manage a wide range of image data.

Method 3: Customizing Image Properties

After converting a NumPy array to a PIL image, you might want to customize the image properties, such as size or format. Here’s how you can resize the image after conversion:

import numpy as np
from PIL import Image

# Create a NumPy array
array = np.random.rand(200, 200, 3) * 255
array = array.astype(np.uint8)

# Convert the NumPy array to a PIL image
image = Image.fromarray(array)

# Resize the image
resized_image = image.resize((100, 100))

# Display the resized image
resized_image.show()

In this code, we create a larger 200x200 RGB image and convert it to a PIL image. After the conversion, we use the resize() method to change the dimensions to 100x100 pixels. This allows for flexibility in how the images are presented or processed further.

Output:

Convert a Numpy array to a PIL image and customize image properties

Customizing image properties after conversion can be essential for preparing images for machine learning models or for creating thumbnails for web applications. The Pillow library offers various methods to manipulate images, making it a powerful tool in your image processing toolkit.

Conclusion

In this tutorial, we explored how to convert a NumPy array to a PIL image using the Image.fromarray() function. We covered different scenarios, including RGB and grayscale images, and discussed how to customize image properties after conversion. By mastering these techniques, you can enhance your image processing capabilities in Python, making your projects more efficient and visually appealing.

Whether you’re a beginner or an experienced developer, understanding these methods will empower you to work with images more effectively. So go ahead and experiment with your own images and NumPy arrays!

FAQ

  1. How do I install Pillow and NumPy?
    You can install Pillow and NumPy using the command: pip install pillow numpy.

  2. Can I convert a 2D NumPy array directly to an RGB image?
    No, a 2D NumPy array represents grayscale images. For RGB images, you need a 3D array.

  3. What data type should my NumPy array be for image conversion?
    The NumPy array should be of type uint8, with values in the range of 0-255.

  4. How can I save the converted PIL image to a file?
    You can use the save() method of the PIL image object, like this: image.save(‘filename.png’).

  5. Is it possible to convert images back to NumPy arrays?
    Yes, you can use numpy.array(image) to convert a PIL image back to a NumPy array.

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Author: Suraj Joshi
Suraj Joshi avatar Suraj Joshi avatar

Suraj Joshi is a backend software engineer at Matrice.ai.

LinkedIn

Related Article - Matplotlib Images