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:
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:
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/numpy/save-a-numpy-array-as-an-image-file-using-python.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics