Book Image

NumPy: Beginner's Guide

By : Ivan Idris
Book Image

NumPy: Beginner's Guide

By: Ivan Idris

Overview of this book

Table of Contents (21 chapters)
NumPy Beginner's Guide Third Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
NumPy Functions' References
Index

Time for Action – accessing surface pixel data with NumPy


In this section, we will tile a small image to fill the game screen.

  1. The array2d() function copies pixels into a two-dimensional array (and there is a similar function for three-dimensional arrays). Copy the pixels from the avatar image into an array:

    pixels = pygame.surfarray.array2d(img)
  2. Create the game screen from the shape of the pixels array using the shape attribute of the array. Make the screen 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 the tile() function. The data needs to be converted into integer values, because Pygame defines colors 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)

    The following code performs the tiling of the image:

    import pygame, sys
    from...