5 Best Ways to Convert Python NumPy Arrays to PNG Images

πŸ’‘ Problem Formulation:

Converting NumPy arrays to PNG images is a common task in the realm of data visualization and image processing. Whether it’s to save the output of a scientific computation, visualize image transformations, or store an array of pixel data as an image file, a reliable conversion method is necessary. Typically, you might start with a two or three-dimensional NumPy array representing pixel intensities and desire to convert this data into a portable network graphics (PNG) image file.

Method 1: Using matplotlib.pyplot.imsave

Matplotlib’s imsave function allows for easy saving of arrays as images. It’s perfect for when you want to quickly export an array as an image without the hassle of dealing with image writers or format specifications. The function will automatically scale the array data to fit the color space of the image.

β™₯️ Info: Are you AI curious but you still have to create real impactful projects? Join our official AI builder club on Skool (only $5): SHIP! - One Project Per Month

Here’s an example:

import numpy as np
import matplotlib.pyplot as plt

# Creating a random NumPy array
array = np.random.rand(100, 100)

# Save as PNG
plt.imsave('array_image.png', array)

The output is a PNG image named ‘array_image.png’ saved to your current directory.

This code snippet creates a 100×100 array of random values and saves it to an image using Matplotlib’s imsave function. The result is a grayscale PNG image where the intensity of each pixel corresponds to the value in the NumPy array.

Method 2: Using imageio.imwrite

Imageio is a powerful Python library that provides an easy interface to write NumPy arrays to various image formats, PNG included. It supports a wide range of image formats and is efficient for routine image writing tasks.

Here’s an example:

import numpy as np
import imageio

# Creating a random NumPy array
array = np.random.rand(100, 100)

# Save as PNG
imageio.imwrite('array_image.png', array)

The output is a PNG file ‘array_image.png’ saved to your current directory.

This snippet uses the imwrite function from the imageio library to save a 100×100 array with random floating-point numbers into a PNG image. This method is straightforward and does not require significant setup or additional context.

Method 3: Using PIL/Pillow

The Python Imaging Library (PIL), now known as Pillow, is a widely-used library that opens up a realm of image processing capabilities in Python, including saving NumPy arrays as images.

Here’s an example:

from PIL import Image
import numpy as np

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

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

# Save as PNG
image.save('array_image.png')

The output is a PNG image file named ‘array_image.png’ in your current directory.

The code begins by creating a random array and scaling the values to cover the full 8-bit grayscale range. After converting the NumPy array into a PIL Image object, the save method is called to store the image as a PNG file.

Method 4: Using OpenCV

OpenCV is a comprehensive library focused on real-time computer vision applications and can be also used to save NumPy arrays as images. It’s a great choice when working with image and video data.

Here’s an example:

import numpy as np
import cv2

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

# Save as PNG using OpenCV
cv2.imwrite('array_image.png', array)

The output is a PNG file ‘array_image.png’ residing in the working directory.

After creating an array with unsigned 8-bit integers, the imwrite function of OpenCV is used to save the array as a PNG image. OpenCV handles the conversion efficiently, making it suitable for computer vision tasks where such an operation might be frequent.

Bonus One-Liner Method 5: Using numpy.save with a Custom One-Liner

If you’re looking for a quick and dirty one-liner to convert and save a NumPy array as a PNG, you can do so with a combination of numpy.save and chaining.

Here’s an example:

import numpy as np
from PIL import Image

# Creating a random NumPy array and saving as PNG in one line
Image.fromarray((np.random.rand(100, 100) * 255).astype('uint8')).save('array_image.png')

The output is an image file ‘array_image.png’ saved in the current directory.

This compact snippet does everything in one line: it generates a random NumPy array, converts it to an unsigned 8-bit array, transforms it into a PIL Image, and saves it as a PNG. It’s not the most readable, but it gets the job done quickly.

Summary/Discussion

  • Method 1: Matplotlib’s imsave. Strengths: Simplicity, integration with plotting library, automatic scaling. Weaknesses: Limited customization of the image saving process.
  • Method 2: Imageio’s imwrite. Strengths: Supports a variety of formats, concise syntax. Weaknesses: Requires an additional library, might be overkill for simple tasks.
  • Method 3: PIL/Pillow. Strengths: Offers advanced image manipulation capabilities, well-established library. Weaknesses: Requires conversion from NumPy array to PIL Image object.
  • Method 4: OpenCV. Strengths: Excellent for computer vision tasks, efficient conversions. Weaknesses: Slightly more cumbersome for simple image saving if not already using OpenCV in the project.
  • Bonus Method 5: One-liner with PIL. Strengths: Quick and compact for simple tasks. Weaknesses: Less readable and harder to debug or modify.