August 2017
Intermediate to advanced
280 pages
6h 19m
English
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):
defoverlay_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 : intThe 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]returnimage_griddedplt.imshow(overlay_grid(astro,128));
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.
This is the solution for “Exercise: Conway’s Game of Life”.
Nicolas Rougier (@NPRougier) ...