w3resource

Save a NumPy array as an image file using Python


19. Save Array as Image File

Write a NumPy program that saves a NumPy array as an image file (e.g., PNG) using an image processing library like PIL or opencv.

Sample Solution:

Python Code:

from PIL import Image
import numpy as np

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

# Define the file name to save the image
image_file_name = 'saved_image.png'

# Convert the NumPy array to an image object
image = Image.fromarray(array_data)

# Save the image object to a PNG file
image.save(image_file_name)

# Verify by loading and displaying the saved image (optional)
loaded_image = Image.open(image_file_name)
loaded_image.show()

Output:

Save a NumPy array as an image file using Python

Explanation:

  • Import Libraries:
    • Imported Image from the PIL library for image processing.
    • Imported numpy as np for handling arrays.
  • Create NumPy Array:
    • Created a 100x100 NumPy array with random values scaled to the 0-255 range.
    • Converted the array to uint8 type suitable for image data.
  • Define Image File Name:
    • Set the file name for saving the image as saved_image.png.
  • Convert Array to Image:
    • Converted the NumPy array to a Pillow image object using Image.fromarray.
  • Save Image File:
    • Saved the image object to a PNG file using the save method.
  • Verify by Loading and Displaying:
    • Optionally loaded the saved image using Image.open and displayed it using show to verify the saved file.

For more Practice: Solve these Related Problems:

  • Write a Numpy program to convert a numeric array into an image and save it as a PNG file using an image processing library.
  • Write a Numpy program to generate a heatmap from a 2D array and export it as an image file in PNG format.
  • Write a Numpy program to modify a grayscale image stored as an array and then save the modified image with a new file name.
  • Write a Numpy program to create an RGB image from three separate arrays and then export the combined image to a PNG file.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Read PNG image data into NumPy array using Python.
Next: Save and load NumPy array to CSV with custom delimiter.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.