NumPy: Convert a numpy array to an image
Convert NumPy Array to Image
Write a NumPy program to convert a NumPy array to an image. Display an image.
Sample Solution:
Python Code:
# Importing the Image module from the PIL library
from PIL import Image
# Importing the NumPy library and aliasing it as 'np'
import numpy as np
# Defining image width and height
img_w, img_h = 200, 200
# Creating a NumPy array 'data' filled with zeros of shape (img_h, img_w, 3) representing RGB channels
data = np.zeros((img_h, img_w, 3), dtype=np.uint8)
# Setting a specific pixel (100, 100) in the 'data' array to the color red [255, 0, 0]
data[100, 100] = [255, 0, 0]
# Creating an image object 'img' from the NumPy array 'data', specifying the color mode as 'RGB'
img = Image.fromarray(data, 'RGB')
# Saving the image as 'test.png'
img.save('test.png')
# Displaying the image
img.show()
Sample Output:
Explanation:
In the above code –
- img_w, img_h = 200, 200: Set the image width and height to 200 pixels.
- data = np.zeros((img_h, img_w, 3), dtype=np.uint8): Create a NumPy array of zeros with the shape (img_h, img_w, 3) representing an image of size 200x200 with 3 color channels (RGB). The data type is set to np.uint8, which means each color channel value will be an 8-bit unsigned integer (0-255).
- data[100, 100] = [255, 0, 0]: Set the pixel at row 100 and column 100 to red. The red channel value is set to 255, while the green and blue channel values are set to 0.
- img = Image.fromarray(data, 'RGB'): Convert the NumPy array 'data' to a PIL Image object with the mode 'RGB' (red, green, blue). Store the resulting image in the variable 'img'.
- img.save('test.png'): Save the PIL Image object 'img' as a PNG file named 'test.png'.
- Finally ‘img.show()’ displays the image using the default image viewer on user system.
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics