NumPy: Create a white image of size 512x256
NumPy: Array Object Exercise-161 with Solution
Write a NumPy program to create a white image of size 512x256.
Sample Solution:
Python Code:
# Importing necessary libraries: PIL for handling images and NumPy for array manipulation
from PIL import Image
import numpy as np
# Creating a NumPy array filled with white color (255) of size 512x256 with three color channels (RGB)
a = np.full((512, 256, 3), 255, dtype=np.uint8)
# Creating an image from the NumPy array
image = Image.fromarray(a, "RGB")
# Saving the image as "white.png" in PNG format
image.save("white.png", "PNG")
Sample Output:
Explanation:
PIL module: The Python Imaging Library (PIL) adds image processing capabilities to your Python interpreter. The library provides extensive file format support, an efficient internal representation, and fairly powerful image processing capabilities.
The core image library is designed for fast access to data stored in a few basic pixel formats. It should provide a solid foundation for a general image processing tool.
In the above code -
- First import the necessary libraries: Image from PIL and numpy as np.
- a = np.full((512, 256, 3), 255, dtype=np.uint8): This line creates a NumPy array ‘a’ with dimensions (512, 256, 3) and fill it with the value 255. The dimensions represent the height, width, and number of color channels (RGB) of the image, respectively. The dtype is set to np.uint8, which means that each element of the array will be an 8-bit unsigned integer.
- image = Image.fromarray(a, "RGB"): Here Image.fromarray method is used to create an image object image from the NumPy array ‘a’. The second argument, "RGB", specifies that the input array has three color channels.
- image.save("white.png", "PNG"): Save the image object as a PNG file named "white.png" using the save method.
Python-Numpy Code Editor:
Previous: Write a NumPy program to find the k smallest values of a given numpy array.
Next: Write a NumPy program to select from the first axis (K) by the indices tidx to get an array of shape (J=4, I=8) back.
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://w3resource.com/python-exercises/numpy/python-numpy-exercise-161.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics