Create an art or image by yourself using arrays and Numpy
Introduction
- NumPy is like a superhero library for numbers in Python! It helps us work with arrays, which are like special lists that can do amazing math tricks.
- Imagine you have a lot of numbers and want to do math operations with them. NumPy comes to the rescue with its “array” superpower. Arrays are like organized collections of numbers that can be easily added, subtracted, multiplied, and divided, just like magic!
- With NumPy, you can perform complex math tasks quickly and efficiently. It’s like having a math wizard by your side, making your calculations faster and your code easier to write.
Code:
import numpy as np
import matplotlib.pyplot as plt
# Define the dimensions of the kingdom
width = 10
height = 10
# Create a canvas (2D array) filled with grass color
canvas = np.ones((height, width, 3)) * [0.4, 0.8, 0.2] # Light green for grass
# Add a river
canvas[3:7, :] = [0.2, 0.6, 0.8] # Light blue for the river
# Add a castle
canvas[2:5, 2:8] = [0.8, 0.4, 0.2] # Light brown for the castle
# Add some houses
canvas[6, 1] = [0.8, 0.6, 0.2] # Light yellow for a house
canvas[7, 3] = [0.8, 0.6, 0.2] # Light yellow for another house
canvas[6, 8] = [0.8, 0.6, 0.2] # Light yellow for one more house
# Display the kingdom
plt.imshow(canvas)
plt.axis(‘off’) # Turn off axis ticks and labels
plt.show()
Output:
Code with Ouput:
Break down of the code(kingdom image):
- Here, we are importing two libraries, NumPy and matplotlib.pyplot. NumPy helps us work with arrays, and matplotlib.pyplot helps us visualize the image.
- We define the dimensions of the kingdom as 10 units wide and 10 units high.
- We create a canvas, which is like a blank sheet, filled with a light green color representing grass. The canvas is a 2D array with dimensions 10x10x3 (height, width, and three channels for RGB colors).
- We add a river to the canvas. This line of code changes the color of rows 3 to 6 to a light blue color, creating a river in the kingdom.
- We add a castle to the canvas. This line of code changes the color of a specific area (rows 2 to 4 and columns 2 to 7) to a light brown color, creating a castle in the kingdom.
- We add some houses to the canvas. Each line of code changes the color of a specific pixel to a light yellow color, creating houses in the kingdom.
- Finally, we use matplotlib.pyplot to display the canvas as an image. The imshow() function shows the canvas, and plt.axis(‘off’) turns off the axis ticks and labels for a cleaner image display. plt.show() is used to display the image on the screen.