Create an art or image by yourself using arrays and Numpy

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

from PIL import Image

width, height = 400, 400

image = np.zeros((height, width), dtype=np.uint8)

square_size = width // 8

for i in range(8):

for j in range(8):

if (i + j) % 2 == 0:

image[i square_size:(i + 1) square_size, j square_size:(j + 1) square_size] = 255

image = Image.fromarray(image)

image.save("checkerboard.png")

image.show()

Article content

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.

To view or add a comment, sign in

More articles by Ankit Kumar

Explore content categories