---
title: "Grids and Images"
book: "Primary & Middle School Computer Science"
subject: computer-science
language: en
chapter: 33
exercises: 12
source: https://one-course.com/books/computer-science/1/en/chapter/33-grids-and-images
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 33 — Grids and Images

Noor zooms into a photo on her tablet, again and again, until the face of her cat turns into small coloured squares. Each square is a [pixel](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-pixel), and each [pixel](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-pixel) is a number, or three. A photo is a table of numbers with rows and columns: a [grid](#def-g9-grids-and-images-grid). This chapter builds [grids](#def-g9-grids-and-images-grid) in Python, and changes pictures by changing their numbers.

**You already know.**

A [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) keeps [values](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) in order, each at an [index](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) from 0; a [slice](https://one-course.com/books/computer-science/1/en/chapter/21-strings#def-g7-strings-slice) such as `items[::-1]` reads it backwards ([Chapter 20](https://one-course.com/books/computer-science/1/en/chapter/20-lists#ch-g7-lists)). A picture is made of [pixels](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-pixel); a [grey level](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-grey) is a number from 0 (black) to 255 (white); a colour is three numbers, red, green and blue ([Chapter 12](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#ch-g5-text-pictures-sound-as-numbers)). A [text file](https://one-course.com/books/computer-science/1/en/chapter/27-files-and-data-tables#def-g8-files-and-data-tables-text-file) can be read and written by a [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) ([Chapter 27](https://one-course.com/books/computer-science/1/en/chapter/27-files-and-data-tables#ch-g8-files-and-data-tables)).

## 33.1 A list of lists as a grid

**Definition 33.1 (Grid).**

A *grid* is a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of [lists](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of the same length: each inner [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) is one row, and the [values](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) at the same [index](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) in every row form a column. `grid[r][c]` is the [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) in row `r`, column `c`.

**Definition 33.2 (Grid cell).**

A *grid cell* is one place of a [grid](#def-g9-grids-and-images-grid), given by its row and its column.

```python
grid = [[3, 8, 1, 6],
        [7, 2, 9, 4],
        [5, 0, 4, 2]]
print("rows:", len(grid), " columns:", len(grid[0]))
print("grid[1][2] =", grid[1][2])
grid[1][2] = 0
print("row 1 is now", grid[1])

zeros = []
for _ in range(2):
    row = []
    for _ in range(3):
        row.append(0)
    zeros.append(row)
print(zeros)
```

***Listing 33.1.** A [grid](#def-g9-grids-and-images-grid) of 3 rows and 4 columns, and a [grid](#def-g9-grids-and-images-grid) built by [loops](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop). code/grade-9/03-grids-and-images/listings/grid_basics.py*

```
$ python grid_basics.py
rows: 3  columns: 4
grid[1][2] = 9
row 1 is now [7, 2, 0, 4]
[[0, 0, 0], [0, 0, 0]]
```

***Output 33.1.** Rows first, then columns.*

`grid[1]` is the row `[7, 2, 9, 4]`, and `grid[1][2]` the [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) at [index](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) 2 of that row. `len(grid)` counts the rows, `len(grid[0])` the [values](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) of a row, so the columns.

![The grid of : row 1, column 2 holds 9 (before it is changed to 0).](https://one-course.com/images/onecourse/chapters/computer-science-1/g9-grids-and-images/fig-f659ebd6f927.svg)

*The [grid](#def-g9-grids-and-images-grid) of [Listing 33.1](#lst-g9-grids-and-images-basics): row 1, column 2 holds 9 (before it is changed to 0).*

To show a [grid](#def-g9-grids-and-images-grid) as a table, print each row on its own line:

```python
grid = [[3, 8, 1, 6],
        [7, 2, 9, 4],
        [5, 0, 4, 2]]
for r in range(len(grid)):
    line = ""
    for c in range(len(grid[r])):
        line = line + f"{grid[r][c]:>3}"
    print(line)
```

***Listing 33.2.** Printing a [grid](#def-g9-grids-and-images-grid) row by row. code/grade-9/03-grids-and-images/listings/print_grid.py*

```
$ python print_grid.py
  3  8  1  6
  7  2  9  4
  5  0  4  2
```

***Output 33.2.** The [grid](#def-g9-grids-and-images-grid) as a table.*

A short way to build a [grid](#def-g9-grids-and-images-grid) of zeros looks tempting, but it holds a trap:

```python
trap = [[0] * 3] * 3
trap[0][0] = 1
print(trap)

safe = []
for _ in range(3):
    safe.append([0] * 3)
safe[0][0] = 1
print(safe)
```

***Listing 33.3.** Two ways to build a [grid](#def-g9-grids-and-images-grid) of zeros. code/grade-9/03-grids-and-images/listings/shared_rows.py*

```
$ python shared_rows.py
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
[[1, 0, 0], [0, 0, 0], [0, 0, 0]]
```

***Output 33.3.** One change appears in every row of the first [grid](#def-g9-grids-and-images-grid).*

`[[0] * 3] * 3` is the *same* row three times, not three rows: a change to one is a change to all. The [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) builds a new row at each turn. Why Python works this way is explained in the next book; for now, build [grids](#def-g9-grids-and-images-grid) with a [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop).

## 33.2 Neighbours

**Definition 33.3 (Neighbour of a cell).**

The *neighbours* of a [grid cell](#def-g9-grids-and-images-cell) are the cells that touch it: the four above, below, left and right of it, or the eight that also include the corners. A cell at the edge of the [grid](#def-g9-grids-and-images-grid) has fewer.

The eight [neighbours](#def-g9-grids-and-images-neighbour) of `grid[r][c]` are found by adding $-1$, 0 or 1 to the row and to the column, skipping the cell itself and the places outside the [grid](#def-g9-grids-and-images-grid):

```python
def neighbours(grid, r, c):
    """The values of the up to eight cells around grid[r][c], inside the grid."""
    found = []
    for dr in [-1, 0, 1]:
        for dc in [-1, 0, 1]:
            nr = r + dr
            nc = c + dc
            inside = 0 <= nr < len(grid) and 0 <= nc < len(grid[0])
            if (dr != 0 or dc != 0) and inside:
                found.append(grid[nr][nc])
    return found


grid = [[3, 8, 1, 6],
        [7, 2, 9, 4],
        [5, 0, 4, 2]]
print("around grid[1][1]:", neighbours(grid, 1, 1))
print("around grid[0][0]:", neighbours(grid, 0, 0))
big = 0
for value in neighbours(grid, 1, 2):
    if value >= 5:
        big = big + 1
print("neighbours of grid[1][2] that are 5 or more:", big)
```

***Listing 33.4.** The [neighbours](#def-g9-grids-and-images-neighbour) of a cell. code/grade-9/03-grids-and-images/listings/neighbours.py*

```
$ python neighbours.py
around grid[1][1]: [3, 8, 1, 7, 9, 5, 0, 4]
around grid[0][0]: [8, 7, 2]
neighbours of grid[1][2] that are 5 or more: 2
```

***Output 33.4.** A middle cell has 8 [neighbours](#def-g9-grids-and-images-neighbour), a corner 3.*

![A cell (red) and its neighbours (blue): the four that share a side, the eight that also share a corner, and the three of a corner cell.](https://one-course.com/images/onecourse/chapters/computer-science-1/g9-grids-and-images/fig-f009dbed9575.svg)

*A cell (red) and its [neighbours](#def-g9-grids-and-images-neighbour) (blue): the four that share a side, the eight that also share a corner, and the three of a corner cell.*

The test `0 <= nr < len(grid)` checks both ends at once: `nr` is at least 0 *and* smaller than the number of rows.

## 33.3 A grey-level image as a grid

A grey-level image is a [grid](#def-g9-grids-and-images-grid) of [grey levels](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-grey), one per [pixel](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-pixel): row 0 is the top of the image. A colour image is three [grids](#def-g9-grids-and-images-grid) of the same size, one for red, one for green, one for blue. The rest of the chapter uses [grey levels](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-grey), one [grid](#def-g9-grids-and-images-grid).

## 33.4 A plain-text image file

**Definition 33.4 (PGM file).**

A *plain PGM file* is a [text file](https://one-course.com/books/computer-science/1/en/chapter/27-files-and-data-tables#def-g8-files-and-data-tables-text-file) that holds a grey-level image: the letters `P2`, then the width and the height, then the largest [grey level](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-grey) (255), then the [grey level](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-grey) of every [pixel](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-pixel), row after row, separated by spaces or ends of line.

The format is one of a family of very simple image formats, made to be read and written easily by [programs](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program); its documentation asks for lines of at most 70 [characters](https://one-course.com/books/computer-science/1/en/chapter/21-strings#def-g7-strings-string). A small [file](https://one-course.com/books/computer-science/1/en/chapter/7-files-and-folders#def-g3-files-and-folders-file) of 6 by 4 [pixels](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-pixel), from black to white:

```python
from pgm import pgm_text

image = []
for _ in range(4):
    row = []
    for c in range(6):
        row.append(c * 51)           # from black (0) to white (255), left to right
    image.append(row)
print(pgm_text(image))
```

***Listing 33.5.** A small image as PGM text. code/grade-9/03-grids-and-images/listings/make_image.py*

```
$ python make_image.py
P2
6 4
255
   0  51 102 153 204 255
   0  51 102 153 204 255
   0  51 102 153 204 255
   0  51 102 153 204 255
```

***Output 33.5.** Six columns, from 0 to 255.*

Two [functions](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) read and write the format. `read_pgm` splits the whole text into words, reads the width and the height, and fills the [grid](#def-g9-grids-and-images-grid); the [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) of row `r`, column `c` is word number `r * width + c` after the header. `pgm_text` does the reverse.

```python
def read_pgm(filename):
    """The grey levels of a plain PGM file, as a grid of whole numbers."""
    with open(filename, encoding="utf-8") as f:
        words = f.read().split()
    width = int(words[1])
    height = int(words[2])
    values = words[4:]                   # after P2, width, height and 255
    grid = []
    for r in range(height):
        row = []
        for c in range(width):
            row.append(int(values[r * width + c]))
        grid.append(row)
    return grid


def pgm_text(grid):
    """The text of a plain PGM file holding the grid."""
    lines = ["P2", str(len(grid[0])) + " " + str(len(grid)), "255"]
    for row in grid:
        line = ""
        for value in row:
            line = line + f"{value:>4}"
        lines.append(line)
    return "\n".join(lines)
```

***Listing 33.6.** Reading and writing the plain PGM format. code/grade-9/03-grids-and-images/listings/pgm.py*

The chapter’s image is `shape.pgm`, 16 by 12 [pixels](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-pixel): a dark background, a grey square and a white arrow. A script of the chapter writes it, and a test checks that it is written the same way every time.

```python
from pgm import read_pgm

image = read_pgm("shape.pgm")
print(len(image[0]), "x", len(image), "pixels")
print("top left:", image[0][0], " arrow tip:", image[6][14])
print("row 6:", image[6])
```

***Listing 33.7.** Reading the chapter’s image. code/grade-9/03-grids-and-images/listings/read_pgm.py*

```
$ python read_pgm.py
16 x 12 pixels
top left: 40  arrow tip: 230
row 6: [40, 40, 40, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 40]
```

***Output 33.6.** Row 6 runs through the middle of the arrow.*

## 33.5 Changing an image

Each change below reads `shape.pgm`, changes the [grid](#def-g9-grids-and-images-grid), and prints the text of the new [PGM file](#def-g9-grids-and-images-pgm); the pictures at the end of the section are drawn from that printed text. The *negative* replaces each [grey level](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-grey) $v$ by $255 - v$:

```python
from pgm import pgm_text, read_pgm

image = read_pgm("shape.pgm")
for r in range(len(image)):
    for c in range(len(image[r])):
        image[r][c] = 255 - image[r][c]
print(pgm_text(image))
```

***Listing 33.8.** The negative. code/grade-9/03-grids-and-images/listings/negative.py*

The *mirror* reads each row backwards, so left and right swap:

```python
from pgm import pgm_text, read_pgm

image = read_pgm("shape.pgm")
for r in range(len(image)):
    image[r] = image[r][::-1]          # each row read backwards
print(pgm_text(image))
```

***Listing 33.9.** The mirror. code/grade-9/03-grids-and-images/listings/mirror.py*

**Method 33.5 (Threshold).**

To turn a grey image into pure black and white, choose a level, such as 128: every [pixel](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-pixel) at that level or above becomes white (255), every other [pixel](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-pixel) black (0).

```python
from pgm import pgm_text, read_pgm

image = read_pgm("shape.pgm")
for r in range(len(image)):
    for c in range(len(image[r])):
        if image[r][c] >= 128:
            image[r][c] = 255
        else:
            image[r][c] = 0
print(pgm_text(image))
```

***Listing 33.10.** The threshold at 128. code/grade-9/03-grids-and-images/listings/threshold.py*

**Method 33.6 (Blur by averaging).**

To blur an image, replace each [pixel](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-pixel) by the average of the 3 by 3 square around it: itself and its [neighbours](#def-g9-grids-and-images-neighbour), fewer at the edges. Sharp edges become soft slopes.

![The 3 by 3 window of the blur: the new grey level of a pixel is the average of the window around it.](https://one-course.com/images/onecourse/chapters/computer-science-1/g9-grids-and-images/fig-036aa7d1eedb.svg)

*The 3 by 3 window of the blur: the new [grey level](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-grey) of a [pixel](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-pixel) is the average of the window around it.*

```python
from pgm import pgm_text, read_pgm


def blur(image):
    """Each pixel becomes the average of itself and its neighbours, rounded."""
    new = []
    for r in range(len(image)):
        row = []
        for c in range(len(image[0])):
            total = 0
            count = 0
            for dr in [-1, 0, 1]:
                for dc in [-1, 0, 1]:
                    if 0 <= r + dr < len(image) and 0 <= c + dc < len(image[0]):
                        total = total + image[r + dr][c + dc]
                        count = count + 1
            row.append(round(total / count))
        new.append(row)
    return new


if __name__ == "__main__":
    print(pgm_text(blur(read_pgm("shape.pgm"))))
```

***Listing 33.11.** The blur: a new [grid](#def-g9-grids-and-images-grid), filled from the old one. code/grade-9/03-grids-and-images/listings/blur.py*

The blur builds a *new* [grid](#def-g9-grids-and-images-grid). If it changed the old one in place, each average would use [pixels](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-pixel) already blurred, and the result would depend on the order of the [loops](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop).

![The chapter’s image and its four changes, drawn from the grey levels that the programs printed.](https://one-course.com/images/onecourse/chapters/computer-science-1/g9-grids-and-images/fig-09684348c067.svg)

*The chapter’s image and its four changes, drawn from the [grey levels](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-grey) that the [programs](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) printed.*

## 33.6 Exercises

**Exercise 33.1 ★.**

In the [grid](#def-g9-grids-and-images-grid) of [Output 33.2](#out-g9-grids-and-images-print), what is `grid[2][0]`? And `grid[0][3]`?

**Solution of Exercise 33.1.**

`grid[2][0]` is 5, the first [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) of the last row; `grid[0][3]` is 6, the last [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) of the first row.

**Exercise 33.2 ★.**

Which [values](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) does `neighbours(grid, 2, 3)` return for the same [grid](#def-g9-grids-and-images-grid)?

**Solution of Exercise 33.2.**

`[9, 4, 4]`: the cell is the bottom right corner, so only three cells touch it, `grid[1][2]`, `grid[1][3]` and `grid[2][2]`.

**Exercise 33.3 ★.**

`negative.py` is run on a 2 by 2 image whose rows are `0 100` and `200 255`. What are the [grey levels](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-grey) of the result?

**Solution of Exercise 33.3.**

Rows `255 155` and `55 0`: black and white swap, and each grey goes to its opposite.

**Exercise 33.4 ★.**

Write a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `transpose(grid)` that returns the [grid](#def-g9-grids-and-images-grid) whose rows are the columns of `grid`.

**Solution of Exercise 33.4.**

Column `c` of the old [grid](#def-g9-grids-and-images-grid) becomes row `c` of the new one:

```python
def transpose(grid):
    """The grid whose rows are the columns of grid."""
    new = []
    for c in range(len(grid[0])):
        row = []
        for r in range(len(grid)):
            row.append(grid[r][c])
        new.append(row)
    return new
```

*Rows and columns swapped. code/grade-9/03-grids-and-images/exercises/transpose.py*

**Exercise 33.5 ★★.**

This [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) stops with an `IndexError` for the bottom right cell, and gives a wrong answer, with no error, for the top left one. Why? Fix it.

```python
def neighbours4(grid, r, c):
    return [grid[r - 1][c], grid[r + 1][c], grid[r][c - 1], grid[r][c + 1]]
```

***Listing 33.12.** Four [neighbours](#def-g9-grids-and-images-neighbour), without checks. code/grade-9/03-grids-and-images/exercises/neighbours_bug.py*

**Solution of Exercise 33.5.**

For the bottom right cell, `grid[r + 1]` asks for a row that does not exist. For the top left one, `grid[r - 1]` is `grid[-1]`: a negative [index](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) counts from the end, so Python quietly reads the last row, and `grid[0][-1]` the last column. The fix keeps only the places inside the [grid](#def-g9-grids-and-images-grid):

```python
def neighbours4(grid, r, c):
    """The values above, below, left and right of grid[r][c], inside the grid."""
    found = []
    for place in [[r - 1, c], [r + 1, c], [r, c - 1], [r, c + 1]]:
        nr = place[0]
        nc = place[1]
        if 0 <= nr < len(grid) and 0 <= nc < len(grid[0]):
            found.append(grid[nr][nc])
    return found
```

*Four [neighbours](#def-g9-grids-and-images-neighbour), inside the [grid](#def-g9-grids-and-images-grid) only. code/grade-9/03-grids-and-images/exercises/neighbours_fixed.py*

**Exercise 33.6 ★★.**

This mirror returns `image[::-1]`. What does it do to the arrow of `shape.pgm`? Fix it.

**Solution of Exercise 33.6.**

`image[::-1]` reverses the order of the rows: the image is turned upside down. The arrow still points right, one row higher, and the grey square moves to the bottom. A mirror reverses each row, as in [Listing 33.9](#lst-g9-grids-and-images-mirror).

**Exercise 33.7 ★★.**

Write a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `brighter(image, amount)` that adds `amount` to every [grey level](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-grey), keeping each result between 0 and 255.

**Solution of Exercise 33.7.**

```python
def brighter(image, amount):
    """Add amount to every grey level, kept between 0 and 255."""
    new = []
    for row in image:
        new_row = []
        for value in row:
            value = value + amount
            if value > 255:
                value = 255
            if value < 0:
                value = 0
            new_row.append(value)
        new.append(new_row)
    return new
```

*Brighter, kept between 0 and 255. code/grade-9/03-grids-and-images/exercises/brighter.py*

A negative `amount` makes the image darker.

**Exercise 33.8 ★★.**

Write a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `rotate(image)` that turns an image a quarter turn clockwise. What are the width and the height of the result?

**Solution of Exercise 33.8.**

The first row of the result is the first column, read from the bottom up:

```python
def rotate(image):
    """The image turned a quarter turn clockwise."""
    height = len(image)
    new = []
    for c in range(len(image[0])):
        row = []
        for r in range(height):
            row.append(image[height - 1 - r][c])
        new.append(row)
    return new
```

*A quarter turn clockwise. code/grade-9/03-grids-and-images/exercises/rotate.py*

Width and height swap: `shape.pgm` becomes 12 [pixels](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-pixel) wide and 16 high.

**Exercise 33.9 ★★.**

In a [grid](#def-g9-grids-and-images-grid) of 5 columns and 4 rows, add up the numbers of [four-neighbours](#def-g9-grids-and-images-neighbour) (above, below, left, right) of all the cells. Count without listing all 20 cells.

**Solution of Exercise 33.9.**

Count the pairs of cells side by side: in each of the 4 rows, 4 pairs; in each of the 5 columns, 3 pairs; 31 pairs in all. Each pair counts once for each of its two cells: $2 \times 31 = 62$.

**Exercise 33.10 ★★★.**

Write a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `count_white(image)` that counts the [pixels](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-pixel) at 255. How many are there in the threshold of `shape.pgm`?

**Solution of Exercise 33.10.**

```python
def count_white(image):
    """The number of pixels at 255."""
    count = 0
    for row in image:
        count = count + row.count(255)
    return count
```

*White [pixels](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-pixel). code/grade-9/03-grids-and-images/exercises/count_white.py*

The threshold keeps the 46 [pixels](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-pixel) of the arrow, at 230; the grey square, at 120, becomes black.

**Exercise 33.11 ★★★.**

A [plain PGM file](#def-g9-grids-and-images-pgm) of $w$ by $h$ [pixels](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-pixel) writes each [grey level](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-grey) with at most three digits and a separator. About how many [bytes](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte) does it take, at most? Compare with one [byte](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte) per [pixel](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-pixel).

**Solution of Exercise 33.11.**

At most 4 [characters](https://one-course.com/books/computer-science/1/en/chapter/21-strings#def-g7-strings-string) per [pixel](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-pixel), so about $4wh$ [bytes](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte), plus a dozen for the header. One [byte](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte) per [pixel](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-pixel) would take $wh$: the text format is about four times larger, the price of being readable.

**Exercise 33.12 ★★★.**

A [grid](#def-g9-grids-and-images-grid) of 0s and 1s changes by these rules: a cell at 1 stays at 1 if 2 or 3 of its eight [neighbours](#def-g9-grids-and-images-neighbour) are at 1, and becomes 0 otherwise; a cell at 0 becomes 1 if exactly 3 of its [neighbours](#def-g9-grids-and-images-neighbour) are at 1. Write a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `step(grid)` that returns the next [grid](#def-g9-grids-and-images-grid). Check it on three 1s in a row in the middle of a 5 by 5 [grid](#def-g9-grids-and-images-grid).

**Solution of Exercise 33.12.**

The new [grid](#def-g9-grids-and-images-grid) is built apart from the old one, as for the blur:

```python
def step(grid):
    """One generation: a living cell (1) lives on with 2 or 3 living neighbours;
    an empty cell (0) comes to life with exactly 3."""
    new = []
    for r in range(len(grid)):
        row = []
        for c in range(len(grid[0])):
            alive = 0
            for dr in [-1, 0, 1]:
                for dc in [-1, 0, 1]:
                    nr = r + dr
                    nc = c + dc
                    inside = 0 <= nr < len(grid) and 0 <= nc < len(grid[0])
                    if (dr != 0 or dc != 0) and inside:
                        alive = alive + grid[nr][nc]
            if grid[r][c] == 1 and alive in [2, 3]:
                row.append(1)
            elif grid[r][c] == 0 and alive == 3:
                row.append(1)
            else:
                row.append(0)
        new.append(row)
    return new
```

*One generation. code/grade-9/03-grids-and-images/exercises/life.py*

Three 1s in a row become three 1s in a column, then a row again: the middle cell keeps 2 [neighbours](#def-g9-grids-and-images-neighbour), the two ends have only 1 and die, and the cells above and below the middle have exactly 3 and come to life. A test of the chapter checks both steps.

## 33.7 Problem: The Blur That Spreads

**Problem 33.1.**

Weekend problem — the blur that spreads

A black image holds one white [pixel](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-pixel), 255, in its middle. What happens when it is blurred again and again? In this problem, the window always divides by 9, and the places outside the image count as 0.

**Part I — By hand.**

1. On a 7 by 7 image with the white [pixel](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-pixel) in the middle, which [pixels](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-pixel) are not 0 after one blur? What is their [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) ?
2. After a second blur, how far from the middle does the light reach?
3. Guess the number of lit [pixels](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-pixel) after $k$ blurs, far from the edges.

**Part II — Decimal values.**

```python
def blur(grid, whole):
    """The 3 x 3 average of every cell (cells outside the grid count as 0)."""
    size = len(grid)
    new = []
    for r in range(size):
        row = []
        for c in range(size):
            total = 0
            for dr in [-1, 0, 1]:
                for dc in [-1, 0, 1]:
                    if 0 <= r + dr < size and 0 <= c + dc < size:
                        total = total + grid[r + dr][c + dc]
            if whole:
                row.append(round(total / 9))
            else:
                row.append(total / 9)
        new.append(row)
    return new


def lit(grid):
    """The number of cells that are not 0."""
    count = 0
    for row in grid:
        for value in row:
            if value != 0:
                count = count + 1
    return count
```

***Listing 33.13.** The blur of the problem, and a count of the lit cells. code/grade-9/03-grids-and-images/listings/spread.py*

```python
for whole in [False, True]:
    grid = []
    for _ in range(15):
        grid.append([0] * 15)
    grid[7][7] = 255                       # one white pixel in the middle
    print("whole grey levels:", whole)
    last_change = 0
    for k in range(1, 21):
        new = blur(grid, whole)
        if new != grid:
            last_change = k
        grid = new
        if k <= 6 or k == 20:
            centre = f"{grid[7][7]:.2f}"
            print(f"  after {k:>2} blurs: {lit(grid):>3} cells lit, centre {centre}")
    print("  the image last changed at blur", last_change)
```

***Listing 33.14.** Blurring one white [pixel](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-pixel) 20 times, with decimal and with whole [values](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value). code/grade-9/03-grids-and-images/listings/spread.py*

4. What does `lit` count, and what does the [parameter](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-parameter) `whole` change?
5. Run the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) . Do the counts with decimal [values](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) match your guess?
6. Why are all 225 cells lit after 20 blurs, and not $41 \times 41$ ?
7. Does the total brightness stay the same from blur to blur?

**Part III — Whole grey levels.**

8. A [PGM file](#def-g9-grids-and-images-pgm) stores whole numbers only. How do the counts change with `whole=True` ?
9. Why does the light stop spreading after 5 blurs?
10. After blur 16 the image no longer changes at all. Explain why a blur can leave an image unchanged.
11. What does this tell you about doing a calculation many times with rounded numbers?
12. State the result.

**Solution of Problem 33.1.**

**1.** The 9 [pixels](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-pixel) of the 3 by 3 square around the middle, each at $255 / 9 \approx 28.33$.

**2.** Two [pixels](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-pixel) from the middle in every direction: a 5 by 5 square.

**3.** Each blur adds a ring one [pixel](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-pixel) wide: $(2k + 1) \times (2k + 1)$.

**4.** The [pixels](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-pixel) that are not 0; `whole` rounds each new [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) to a whole [grey level](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-grey), as a [PGM file](#def-g9-grids-and-images-pgm) must.

**5.** Yes: 9, 25, 49, 81, 121, 169, the squares of 3, 5, 7, 9, 11, 13.

```
$ python spread.py
whole grey levels: False
  after  1 blurs:   9 cells lit, centre 28.33
  after  2 blurs:  25 cells lit, centre 28.33
  after  3 blurs:  49 cells lit, centre 17.14
  after  4 blurs:  81 cells lit, centre 14.03
  after  5 blurs: 121 cells lit, centre 11.23
  after  6 blurs: 169 cells lit, centre 9.54
  after 20 blurs: 225 cells lit, centre 2.99
  the image last changed at blur 20
whole grey levels: True
  after  1 blurs:   9 cells lit, centre 28.00
  after  2 blurs:  25 cells lit, centre 28.00
  after  3 blurs:  45 cells lit, centre 17.00
  after  4 blurs:  61 cells lit, centre 13.00
  after  5 blurs:  69 cells lit, centre 11.00
  after  6 blurs:  69 cells lit, centre 9.00
  after 20 blurs:  69 cells lit, centre 3.00
  the image last changed at blur 16
```

***Output 33.7.** Decimal [values](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value), then whole [grey levels](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-grey).*

**6.** The image is only 15 by 15: after 7 blurs, the light reaches the edges, and there are no more [pixels](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-pixel) to light.

**7.** Far from the edges, yes: each [pixel](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-pixel) hands out one ninth of its [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) to each of 9 [pixels](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-pixel), so the total stays 255. Once the light reaches the edges, the share that would go outside is lost.

**8.** The same 9 and 25, then fewer: 45, 61, 69, and 69 again.

**9.** At the border of the lit area, a dark [pixel](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-pixel)’s window holds a few small [values](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value). When their sum is less than 4.5, the average is less than 0.5, and it rounds to 0: the [pixel](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-pixel) stays dark.

**10.** When every [pixel](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-pixel)’s window averages to a [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) that rounds back to the [pixel](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-pixel)’s own [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value), nothing changes, and every later blur gives the same image.

**11.** Rounding errors can stop a process, or keep it where it is, although the exact calculation would go on changing.

**12.** **Result.** With decimal [values](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value), after $k$ blurs exactly $(2k + 1) \times (2k + 1)$ [pixels](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-pixel) are lit, away from the edges. With whole [grey levels](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-grey), the light stops spreading at 69 [pixels](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-pixel) after 5 blurs, and from blur 16 on the image no longer changes at all, its centre stuck at 3.
