Appendix. Exercise Solutions

Solution: Adding a Grid Overlay

This is the solution for “Exercise: Adding a Grid Overlay”.

We can use NumPy slicing to select the rows of the grid, set them to blue, and then select the columns and set them to blue as well (Figure A-1):

def overlay_grid(image, spacing=128):
    """Return an image with a grid overlay, using the provided spacing.

    image : array, shape (M, N, 3)
        The input image.
    spacing : int
        The spacing between the grid lines.

    image_gridded : array, shape (M, N, 3)
        The original image with a blue grid superimposed.
    image_gridded = image.copy()
    image_gridded[spacing:-1:spacing, :] = [0, 0, 255]
    image_gridded[:, spacing:-1:spacing] = [0, 0, 255]
    return image_gridded

plt.imshow(overlay_grid(astro, 128));
Figure A-1. Astronaut image overlaid with a grid

Note that we used -1 to mean the last value of the axis, as is standard in Python indexing. You can omit this value, but the meaning is slightly different. Without it (i.e., spacing::spacing), you go all the way to the end of the array, including the final row/column. When you use it as the stop index, you prevent the final row from being selected. In the case of a grid overlay, this is probably the desired behavior.

Solution: Conway’s Game of Life

This is the solution for “Exercise: Conway’s Game of Life”.

Nicolas Rougier (@NPRougier) ...

Get Elegant SciPy now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.