Time for action – accessing surface pixel data with NumPy

In this tutorial we will tile a small image to fill the game screen. Perform the following steps to do so:

  1. The array2d function copies pixels into a two-dimensional array. There is a similar function for three-dimensional arrays. We will copy the pixels from the avatar image into an array:
    pixels = pygame.surfarray.array2d(img)
  2. Let's create the game screen from the shape of the pixels array using the shape attribute of the array. The screen will be seven times larger in both directions.
    X = pixels.shape[0] * 7
    Y = pixels.shape[1] * 7
    screen = pygame.display.set_mode((X, Y))
  3. Tiling the image is easy with the NumPy tile function. The data needs to be converted to integer values, since colors are defined as integers.
    new_pixels = np.tile(pixels, (7, 7)).astype(int)
  4. The surfarray module has a special function (blit_array) to display the array on the screen.
    pygame.surfarray.blit_array(screen, new_pixels)

    This produces the following screenshot:

    Time for action – accessing surface pixel data with NumPy

    The following code does the tiling of the image:

    import pygame, sys
    from pygame.locals import *
    import numpy as np
    
    pygame.init()
    img = pygame.image.load('head.jpg')
    pixels = pygame.surfarray.array2d(img)
    X = pixels.shape[0] * 7
    Y = pixels.shape[1] * 7
    screen = pygame.display.set_mode((X, Y))
    pygame.display.set_caption('Surfarray Demo')
    new_pixels = np.tile(pixels, (7, 7)).astype(int)
    
    while True: 
        screen.fill((255, 255, 255))
        pygame.surfarray.blit_array(screen, new_pixels)
    
        for event in pygame.event.get():
          if event.type == QUIT:
             pygame.quit()
             sys.exit()
    
        pygame.display.update()

What just happened?

The following is a brief description of the new functions and attributes we used:

Function

Description

pygame.surfarray.array2d (img)

This copies pixel data into a 2D array.

pygame.surfarray.blit_array(screen, new_pixels)

This displays array values on the screen.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset