Coding exercises: getting started

The lectures describe algorithms in pseudocode: plain steps, close to the math, that you can follow without knowing any programming language. To write the algorithms yourself, exercise pages end with a section Code, after the pen-and-paper questions and the demo.

The coding exercises use Rust and a small image library written for this course, imgcourse. It is made to be read, not to be fast. An image is a grid of numbers, and you change it with plain loops that look like the formulas on the slides. You do not need to know Rust well. The exercises use only variables, loops, functions and small arrays, and every task comes with a hint.

1. Install Rust

Install Rust with rustup, following the instructions at https://rustup.rs:

  • on Linux and macOS, one command in a terminal;
  • on Windows, an installer; it may ask you to install the Visual Studio C++ build tools first.

This gives you cargo, the tool that builds, runs and tests Rust programs. Check it in a new terminal:

cargo --version

A good editor is VS Code with the rust-analyzer extension. It shows types and errors as you type, and the documentation of a function when you hover over it.

2. Download the code

Download imageanalysis-code.zip (about 2 MB) and unpack it anywhere. It is one folder, imageanalysis-code:

imageanalysis-code/
  Cargo.toml             lists the projects below (a Cargo "workspace")
  imgcourse/             the image library
  starter/               a first program
  images/                one project per day of the course, named after the day,
    src/kernels/           with one folder per unit inside: here "Filtering & convolution"
    src/fourier/           ...
  edges/                 day 2, "Edges, blobs and ridges"
  ...

Open a terminal in that folder and run the first program:

cargo run -p starter

The first build downloads a few packages (for reading and writing image files) and takes a minute; later builds take seconds. The program prints the size of the course micrograph and writes two pictures to out/starter/. Open them, then open starter/src/main.rs, read it, change something, and run it again.

3. Do an exercise

Each day is one project, named after the day (images for day 1, edges for day 2, …; the list at the end of this page gives them all), with one folder per unit in src/. Every unit has the same files; for the filtering unit of day 1:

File What it is
images/src/kernels/exercise.rs your code: functions whose body is todo!(), each with a description and a hint
images/tests/check/kernels.rs checks, mostly the numbers of the pen-and-paper exercises
images/src/kernels/run.rs runs your functions on real images and writes pictures to out/kernels/
images/src/kernels/solution.rs a model solution; look at it after you have tried

The commands, from the imageanalysis-code folder:

cargo test -p images kernels::                       # check your code: each todo!() fails until you write it
cargo run  -p images -- kernels                      # run it on the micrograph, pictures in out/kernels/
cargo test -p images --features solution kernels::   # the same checks on the model solution
cargo run  -p images --features solution -- kernels  # the model solution's pictures
cargo run  -p images -- --help                       # the units of day 1

kernels:: selects the checks of one unit; leave it out to run the checks of the whole day. Every exercise page gives the exact commands for its unit. A failing check prints what it expected and what your code gave, for example row 3, column 2: got 2.5, expected 3. Work through the functions in order, C1, C2, …; each check is named after the function it tests.

The first build of a day takes a minute or two; after that, only what you changed is rebuilt. Everything that is built goes into the folder target/ (a few hundred MB per day); you can delete it at any time with cargo clean.

4. The library on one page

use imgcourse::*;

let img = samples::cell();              // the course micrograph, 256 × 256, values 0..1
let img = load_gray("my-image.png");    // or any PNG, JPEG or TIFF file, as grey values 0..1

img.width(); img.height();              // the size
img[(x, y)]                             // pixel at column x, row y (both from 0)
out[(x, y)] = 0.5;                      // set a pixel (out must be `let mut out = ...`)
img.get_border(x, y, Border::Clamp)     // x, y may lie outside: Zero, Clamp, Mirror or Wrap

let mut out = Image::new(w, h, 0.0);    // a new w × h image filled with 0
for (x, y) in img.coords() { ... }      // every pixel position, row by row
img.map(|v| 1.0 - v)                    // a new image: the same function on every value
img.map_xy(|x, y, v| ...)               // ... that can also use the position
a.zip_map(&b, |p, q| p - q)             // combine two images pixel by pixel
img.crop(x0, y0, w, h)                  // a piece of the image
img.min(); img.max(); img.mean();       // for images of f32
Image::from_rows(&[[1., 2.], [3., 4.]]) // a small image written out by hand
println!("{img:.2}");                   // print a small image as a table, 2 decimals

save_gray(&img, "out/a.png");           // 0 = black, 1 = white
save_gray_stretched(&img, "out/b.png"); // smallest value black, largest white
save_gray_signed(&img, "out/c.png");    // 0 = grey: for edge filters with negative values

Complex::new(re, im)                    // complex numbers for Fourier: + - * work
Complex::from_angle(theta)              // e^{iθ}
let mut rng = Rng::new(seed);           // random numbers: rng.uniform(), rng.normal()

save_labels(&labels, "out/l.png");      // a label image (u32, 0 = background), one colour per label
let (img, truth) = samples::nuclei(256, 25, 1); // synthetic nuclei and their true labels
Volume::new(w, h, d, 0.0)               // a 3D image: vol[(x, y, z)]

fft::fft2_real(&img)                    // for later days: a fast Fourier transform,
linalg::solve(&a, &b)                   // small linear algebra (least_squares, sym_eigen),
filters::gaussian_blur(&img, sigma)     // smoothing and sampling (bilinear, rmse, psnr),
rng.poisson(mean)                       // and photon counts

Helpers that several units of a day share (test scenes, plots, small data structures) are in the day’s src/common.rs.

Three conventions to remember:

  • Positions. (x, y) is column x from the left and row y from the top, counted from 0. The pen-and-paper exercises count rows and columns from 1, so “row 3, column 2” is (1, 2).
  • Values. Grey values are f32 between 0 (black) and 1 (white). An 8-bit file is divided by 255 when it is read, and a 16-bit file by 65535.
  • Angles. Because y points down, a rotation by a positive angle turns the image clockwise on the screen.

The full documentation of the library, with examples, opens in your browser with cargo doc -p imgcourse --open.

5. Your own project

To use the library in a project of your own, put the project folder next to imgcourse/ (for example in imageanalysis-code/). A minimal Cargo.toml:

[package]
name = "myproject"
version = "0.1.0"
edition = "2021"

[dependencies]
imgcourse = { path = "../imgcourse" }

and src/main.rs:

use imgcourse::*;

fn main() {
    let img = samples::cell();
    let out = img.map(|v| if v > 0.5 { 1.0 } else { 0.0 });
    save_gray(&out, "out/threshold.png");
}

Run it with cargo run in the project folder. If the project lives inside imageanalysis-code, also add its name to members in imageanalysis-code/Cargo.toml; then cargo run -p myproject works from there too.

Just enough Rust

The exercises need only a handful of constructs; the hints show the rest.

let n = 5;                       // a variable; it cannot change ...
let mut sum = 0.0;               // ... unless it is declared mut
for i in 0..n { sum += 1.0; }    // a loop over 0, 1, ..., n − 1
for d in -1..=1isize { }         // -1, 0, 1 (with ..= the end is included)
let x = 3usize;                  // whole numbers for positions: usize (never negative) ...
let left = x as isize - 1;       // ... and isize, which may be negative; convert with `as`
let v = x as f32 * 0.5;          // f32: a decimal number
let k = [[1.0, 2.0], [3.0, 4.0]];  k[1][0]   // fixed-size arrays: row 1, column 0 is 3.0
let mut list = Vec::new(); list.push(2.5);   // a list that grows
let square = |v: f32| v * v;     // a small function without a name (a closure), for map
fn twice(v: f32) -> f32 { 2.0 * v }          // a function; the last line is its result

For more, the free book The Rust Programming Language, chapters 1 to 3, covers everything used here.

Units with coding exercises

Every unit’s exercise page ends with a section Code. In the download, each day is one project, and each unit a folder inside its src/.