w3resource

Save a NumPy array as an image file using Python


NumPy: I/O Operations Exercise-19 with Solution


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.

Python-Numpy Code Editor: