In this article, we have explained the process to convert Numpy array to an Image in format like jpeg or png. We have presented the code Python code as well.
Table of contents:
- Basics of Image
- Code to Convert Numpy array to image
Basics of Image
An Image is a 3D array have the following dimensions:
The number of channels is expected to be set to 3 for RGB images. For black and white images, the number of channels can be set to 1. If images have additional properties such as transparency, then the number of channels will increase.
Irrespective of the number of channels, the image will be saved using the technique and code presented in this article. If the array data is not correct, then the saved image will be corrected.
Code to Convert Numpy array to image
- Import Numpy
import numpy as np
Create a 3D Numpy array with the number of channels set to 3.
height = 500 # can be any value width = 700 # can be any value channel = 3 # should be 3 for RGB images array = np.random.rand(height, width, channel)
If you have a 1D or 2D array, you need to resize the array to a 3D array.
- Convert the array to Unsigned Integer 8 bit data.
image_data = array.astype(np.uint8)
- Specify the filename and save the image data directly
image_filename = "image.jpeg" image_data.save(image_filename)
Following is the complete Python code using Numpy to save a Numpy array as an image:
import numpy as np height = 500 # can be any value width = 700 # can be any value channel = 3 # should be 3 for RGB images array = np.random.rand(height, width, channel) image_data = array.astype(np.uint8) image_filename = "image.jpeg" image_data.save(image_filename)
With this, you have the complete idea of how to save a Numpy array as an image in Python.