Convert a NumPy array to an image
Last Updated :
02 Sep, 2020
NumPy Or numeric python is a popular library for array manipulation. Since images are just an array of pixels carrying various color codes. NumPy can be used to convert an array into image. Apart from NumPy we will be using PIL or Python Image Library also known as Pillow to manipulate and save arrays.
Approach:
- Create a numpy array.
- Reshape the above array to suitable dimensions.
- Create an image object from the above array using PIL library.
- Save the image object in a suitable file format.
Below is the implementation:
Python3
import numpy as np
from PIL import Image as im
def main():
array = np.arange( 0 , 737280 , 1 , np.uint8)
print ( type (array))
print (array.shape)
array = np.reshape(array, ( 1024 , 720 ))
print (array.shape)
print (array)
data = im.fromarray(array)
data.save( 'gfg_dummy_pic.png' )
if __name__ = = "__main__" :
main()
|
Output:
<class 'numpy.ndarray'>
(737280,)
(1024, 720)
[[ 0 1 2 ... 205 206 207]
[208 209 210 ... 157 158 159]
[160 161 162 ... 109 110 111]
...
[144 145 146 ... 93 94 95]
[ 96 97 98 ... 45 46 47]
[ 48 49 50 ... 253 254 255]]
gfg_dummy_pic.png 1024 x 720
Note: Every array can’t be converted into an image because each pixel of an image consist of specific color code and if the given array is not in a suitable format the libraries won’t be able to process it Properly.
Share your thoughts in the comments
Please Login to comment...