Skip to Content
Elegant SciPy
book

Elegant SciPy

by Juan Nunez-Iglesias, Stéfan van der Walt, Harriet Dashnow
August 2017
Intermediate to advanced
280 pages
6h 19m
English
O'Reilly Media, Inc.
Content preview from Elegant SciPy

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.

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

    Returns
    -------
    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));
png
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) ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

SciPy Recipes

SciPy Recipes

Luiz Felipe Martins, Ke Wu, Ruben Oliva Ramos, V Kishore Ayyadevara
Scientific Computing with Python 3

Scientific Computing with Python 3

Claus Führer, Claus Fuhrer, Jan Erik Solem, Olivier Verdier
Mastering SciPy

Mastering SciPy

Francisco Javier Blanco-Silva, Francisco Javier B Silva

Publisher Resources

ISBN: 9781491922927Errata PageSupplemental Content