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:
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.
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.
Go to:
Previous: Read PNG image data into NumPy array using Python.
Next: Save and load NumPy array to CSV with custom delimiter.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.