How to Save a NumPy Array as an Image File

Updated: January 23, 2024 By: Guest Contributor Post a comment

Overview

Working with images in a scientific or analytical context often requires an understanding of how they are represented in programming, which is commonly done through NumPy arrays in Python. Converting these arrays back into images can be essential for visualizing results, storing them for later use, or for processing with image-specific software. In this tutorial, we will explore how to save a NumPy array as an image file using multiple code examples.

Setting up Your Environment

Before we delve into saving NumPy arrays as images, ensure that you have the necessary libraries installed. You’ll need NumPy for array manipulation and PIL or imageio for saving arrays as images.

# Install required libraries if you haven't already 
!pip install numpy pillow imageio

Basic Saving with PIL

The Python Imaging Library (PIL), now known as Pillow, is a popular library for image processing tasks. To start off with the basics, here’s how to save a NumPy array as an image with Pillow.

import numpy as np
from PIL import Image

# Create a simple grayscale image as a NumPy array,
# where values range from 0 to 255
image_array = np.random.randint(0, 255, (100, 100), dtype=np.uint8)

# Convert to an Image object
image = Image.fromarray(image_array)

# Save the image
image.save('simple_grayscale.png')

Latitude/OpenWeather longitude

Let’s breakdown what the above code does:

  • It uses np.random.randint to generate a 100×100 array of random values, simulating grayscale pixel intensity values.
  • Then, Image.fromarray is used to convert the NumPy array to a PIL Image object.
  • Lastly, the save method is used to write the image to the file system.

Saving a Colored Image

Saving a colored image requires a 3-dimensional NumPy array, with the third dimension representing the color channels—typically Red, Green, and Blue (RGB).

import numpy as np
from PIL import Image

# Generate random pixel data
image_array_rgb = np.random.randint(0, 255, (100, 100, 3), dtype=np.uint8)

# Convert to an Image object
image_rgb = Image.fromarray(image_array_rgb, 'RGB')

# Save the RGB image
image_rgb.save('random_rgb.png')

When saving a colored image, we need to specify the mode ‘RGB’ so that Pillow knows how the array data should be interpreted.

Advanced: Saving with Custom Color Maps

If you want to save grayscale images with color maps, such as those used for heatmaps or geological displays, you can use the matplotlib library in addition to Pillow or imageio:

import numpy as np
import matplotlib.pyplot as plt
from PIL import Image

# Generate an intensity map
intensity_map = np.random.random((100, 100))

# Apply a colormap (e.g., 'viridis')
colored_image_array = plt.get_cmap('viridis')(intensity_map)

colored_image_array = (colored_image_array[:, :, :3] * 255).astype(np.uint8)

# Save through Pillow
Image.fromarray(colored_image_array, 'RGB').save('colormap_image.png')

Using ImageIO

imageio is another library that simplifies the process of writing NumPy arrays as images. With imageio, there’s often no need to manually convert arrays to Image objects, as you can save arrays directly.

import numpy as np
import imageio

# Generate random data
image_array = np.random.randint(0, 255, (100, 100), dtype=np.uint8)

# Use imageio to save the array as an image
imageio.imsave('imageio_simple.png', image_array)

imageio.imsave is straightforward for saving images. The function auto-detects the format based on the filename extension provided.

Conclusion

This guide has taken you through the process of saving NumPy arrays to image files with various libraries and methods, ensuring you have the flexibility to handle different requirements. With the usage of libraries like Pillow and imageio, and additional support from matplotlib for color mapping, saving your numerical data as visual images is simple and efficient.