Create a Image by using Numpy ,Arrays and Matplotlib

Ankit Shukla
2 min readJul 31, 2023

--

Greetings and best wishes for an insightful read😇 ,

Hope this blog finds you great and healthy !!😊

Lets begin with brief introduction about me…..

Hi, This is Ankit Shukla and I am working as Automation Engineer in Regulatory Reporting Domain. In this article we will discuss about How e can create an image using numpy and matplotlib?

To create an image using NumPy and arrays, you can use the numpy library to create a 2D array representing the image and then visualize it using matplotlib. Here's a simple example to create a black square image:

import numpy as np
import matplotlib.pyplot as plt

#----Image Creation----#
# Set Image size ie. (height and width in pixels)
image_height = 200
image_width = 200

# Creating a black image using a NumPy array
my_image = np.zeros((image_height, image_width, 3), dtype=np.uint8)

# Show the black image using matplotlib
plt.imshow(my_image)
plt.axis('off') # It helps when Turn off axes to remove the axis ticks and labels
plt.show()
Output

In the above example, we create a black square image with dimensions 200x200 pixels. The image is represented as a NumPy array of shape (200, 200, 3), where the third dimension (3) represents the three color channels (Red, Green, Blue) of the image.

By setting all pixel values to 0, the image becomes completely black. You can modify the pixel values to create different patterns or images. For example, you can draw shapes, gradients, or any specific patterns by changing the values in the array.

If you want to create more complex images, you can modify the pixel values using NumPy array indexing and slicing. For example, to create a red rectangle in the center of the image, you can do:

import numpy as np
import matplotlib.pyplot as plt

#---Google pixels values for Redrectangle----#
#---Set the pixel values for the red rectangle-----#
my_image[50:150, 50:150, 0] = 255 # Set red 255 (full red)
my_image[50:150, 50:150, 1] = 0 # Set green 0 (no green)
my_image[50:150, 50:150, 2] = 0 # Set blue 0 (no blue)

# Display the modified image after your change
plt.imshow(my_image)
plt.axis('off')
plt.show()
output

Thank you so much fro reading this blog……..😊

--

--

Ankit Shukla
Ankit Shukla

Written by Ankit Shukla

| Software Developer | SDET |

No responses yet