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 countsHelpers 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 columnxfrom the left and rowyfrom 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
f32between 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
ypoints 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 resultFor 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/.
- Day 1 (
images): Images, filters and frequencies. Images as arrays & geometric transforms, Filtering & convolution, Images in frequency space, Principal component analysis. - Day 2 (
edges): Edges, blobs and ridges. Edges: Gaussian derivatives and Canny, Scale space, blobs and pyramids, The Hessian: blobs, ridges and saddles, The structure tensor: orientation and corners. - Day 3 (
bitdepth): Bit depth and noise. Quantisation and bit depth, Camera noise, SNR and PSNR, 12- and 16-bit images in practice, Contrast and intensity transforms, Floating point. - Day 4 (
imageformation): Image formation. Image formation and the point spread function, Resolution, sampling and measuring the PSF, Running the model backwards: an ill-posed problem. - Day 5 (
deconvolution): Deconvolution. Linear deconvolution: inverse, Wiener, Tikhonov, Regularisation: what we add, and how much, Richardson–Lucy, 3D, and the PSF, Denoising and what you may measure. - Day 6 (
splines): Splines and NURBS. Polynomial wiggles, piecewise cubics and Bézier curves, B-splines and NURBS, Interpolating, approximating and smoothing splines, Splines on images: interpolation and free-form deformation. - Day 7 (
wavelets): Wavelets. Localised basis functions and the Haar transform, Multiresolution, filter banks and Daubechies wavelets, The 2D wavelet transform and sparsity of images, Denoising by wavelet shrinkage. - Day 8 (
compression): Image compression. Information, entropy and entropy codes, Prediction, dictionaries and lossless formats, Transform coding, the DCT and the KLT, The JPEG pipeline, artefacts and quality metrics, Compression and measurements, JPEG 2000, formats. - Day 9 (
radon): Radon transform and tomography. Projections and the sinogram, Back-projection and the Fourier slice theorem, Filtered back-projection and sampling, Reconstruction as a linear system. - Day 10 (
pdesmooth): Edge-preserving smoothing and PDEs. Smoothing as heat flow: the heat equation and explicit schemes, Edge-stopping diffusion: Perona–Malik, Total variation flow: smoothing as energy descent, Neighbourhood filters in depth: bilateral and non-local means, Filling holes: diffusion and exemplar inpainting, All smoothers on one image. - Day 11 (
sparse): Sparse representations. Sparsity and the ℓ1 penalty, Solving with ℓ1: thresholding iterations and pursuit, Compressed sensing, Fast MRI with compressed sensing, Sparse coding and dictionary learning. - Day 12 (
thresholding): Thresholding. Histograms & a global threshold, Choosing the threshold: Otsu & minimum error, Local thresholds & hysteresis, Evaluation: Dice, ROC & precision–recall. - Day 13 (
morphology): Morphology. Erosion and dilation, Opening, closing & the distance transform, Grey-level morphology: top-hat & gradient, Reconstruction & h-extrema. - Day 14 (
labelling): Labelling. Connectivity and labelling, Region properties and moments, Shape features, Working with label images. - Day 15 (
watershed): Watershed. Images as landscapes: watershed by flooding, The flooding algorithm on a grid, Watershed segmentation of a real image, Splitting touching objects with the distance transform. - Day 16 (
measurements): Measurements. Intensity inside an object, Texture: co-occurrence matrices, Neighbours, parents and children. - Day 17 (
skeleton): Skeletons. Hit-or-miss and thinning, Medial axis, distance transform and reconstruction, From skeleton to graph: pruning and length, Measuring neurons and vessel networks. - Day 18 (
moments): Moments. Moments as projections onto monomials, Normalisation and moment invariants, Better bases: Legendre moments and reconstruction, Zernike moments on the unit disc. - Day 19 (
spatialstats): Spatial statistics of objects. Point patterns and complete spatial randomness, Nearest neighbours and empty space: G, F and J, Ripley’s K, the L function and the pair correlation, Is it more than chance? Simulation envelopes, Two cell types and an uneven density. - Day 20 (
pointdetection): Point detection. Finding spots: filter, then local maxima, How many false spots? Thresholds from noise, Sub-pixel localisation and the Cramér–Rao bound, Crowded spots and evaluating a detector. - Day 21 (
hough): Hough transform. Hough transform: lines, Hough transform: circles, The generalised Hough transform, Hypothesise and verify: RANSAC. - Day 22 (
integral): Integral images. Integral images: any rectangle in four lookups, Box filters & local statistics, Rectangle features, Boosted detectors & the cascade. - Day 23 (
fftreg): FFT registration. Finding a shift by sliding and scoring, Cross-correlation with the FFT, Phase correlation, From a peak to a mosaic. - Day 24 (
keypoints): Keypoints and descriptors. Keypoints: corners and blobs across scale, Describing a keypoint: gradient histograms and bits, Matching descriptors: nearest, ratio and mutual, From matches to a transform: RANSAC, stitching and registration, Aligning point sets: iterative closest point. - Day 25 (
opticalflow): Optical flow. Motion between frames: brightness constancy and the aperture problem, Lucas–Kanade: local least squares and pyramids, Horn–Schunck and evaluating flow, Non-rigid registration. - Day 26 (
tracking): Tracking. From detections to tracks, Motion models and the Kalman filter, Gaps, divisions and lineage trees, Speed, MSD and modes of motion. - Day 27 (
graphcuts): Graph cuts. Segmentation as energy minimisation, Graphs, cuts and maximum flow, Graph-cut segmentation, Spectral partitioning and normalized cuts. - Day 28 (
ising): Ising model and Markov random fields. Energy and probability: the Ising model, Sampling, temperature and the phase transition, Bayesian denoising with an Ising prior, Quadratic smoothing and total variation. - Day 29 (
graphseg): Graph-based segmentation. The random walker, Spanning trees: single linkage and FH, Watershed as a minimum spanning forest, Hierarchical segmentation and merge trees, Superpixels: SLIC and smaller graphs. - Day 30 (
snakes): Snakes and active shape models. Active contours (snakes), The snake as a linear system, Shape models: landmarks, Procrustes and PCA, Active shape models. - Day 31 (
levelsets): Level sets. Curves as level sets, Moving a curve: the level set equation, Edge-based segmentation: geodesic active contours, Region-based segmentation: Chan–Vese. - Day 32 (
dynprog): Dynamic programming. The DP principle: minimal paths on a grid, Closed boundaries: DP in polar coordinates, When there is no order: Dijkstra and live-wire, From Dijkstra to fast marching. - Day 33 (
randomforest): Random forests. Decision trees, Bagging and random forests, Feature tables & feature importance, Pixel classification with a forest. - Day 34 (
svm): Support vector machines. Linear classifiers, Maximum margin and support vectors, Kernel functions and the kernel trick, SVMs for pixel classification. - Day 35 (
gmm): Gaussian mixtures. Feature spaces & k-means, The multivariate Gaussian & mixtures, Fitting a mixture: EM, Mixtures on images. - Day 36 (
neuralnets): Neural networks. Neural networks: matrix, bend, matrix, Learning: loss, gradient descent and backpropagation, Convolutional networks, Segmentation networks. - Day 37 (
training): Training networks in practice. Optimisers and learning rates, Initialisation, normalisation and residual connections, Regularisation and data augmentation, Reading training curves. - Day 38 (
evaluation): Evaluation and statistics. Matching objects: IoU, F1 and average precision, Boundaries, counts and the uncertain ground truth, Honest validation: leakage, splits and domain shift, From measurements to claims. - Day 39 (
vae): Variational autoencoders. From PCA to autoencoders, The variational autoencoder, Generating and exploring images with a VAE. - Day 40 (
gans): GANs and normalising flows. Generative adversarial networks, Training GANs and what goes wrong, Image-to-image translation and hallucination, Normalising flows. - Day 41 (
moderndl): Modern deep learning. From masks to objects, Finding objects as boxes, Attention, transformers and pretrained models, Diffusion models and generated detail. - Day 42 (
selfsup): Learning without labels. Pretext tasks and masked image modelling, Contrastive learning, Self-distillation and foundation models, Self-supervised denoising. - Day 43 (
cellnets): Networks for cells and objects. Star-convex polygons, Flow fields to objects, From an image to a list of objects, Promptable segmentation, Networks and classical pipelines compared. - Day 44 (
finetuning): Fine-tuning and transfer learning. Transfer learning, Fine-tuning strategies, Few labels: annotation and the human in the loop, Domain shift and adaptation. - Day 45 (
diffusion): Diffusion models. Noise levels, denoisers and the score, Samplers, steps, and judging the samples, Conditioning, guidance and latent diffusion, Diffusion priors for inverse problems, Drifting: generating in one step. - Day 46 (
colour): Colour. From a spectrum to three numbers, RGB: gamma, linear maps & white balance, HSV, CIELAB & colour segmentation, Colour for display: maps, merges & decorrelation. - Day 47 (
unmixing): Spectral unmixing. Bleed-through and compensation, Least-squares unmixing, Endmembers: the geometry of mixtures, Stain separation: colour deconvolution. - Day 48 (
colocalisation): Colocalisation. Colocalisation of two channels, Is it more than chance?, Objects instead of pixels, What the microscope does to colocalisation. - Day 49 (
fret): FRET. FRET in pictures: a ruler for nanometres, Three images, two controls: sensitised emission, Acceptor photobleaching, and what an efficiency means, Ratio imaging, biosensors and the noise of a ratio. - Day 50 (
flim): Fluorescence lifetime imaging (FLIM). Lifetimes, decays and photon counting, Fitting decays with few photons, Frequency domain and phasors, FLIM-FRET and metabolic imaging. - Day 51 (
marchingcubes): Marching cubes. 3D images, Level sets & marching squares, Marching cubes, Measuring surfaces. - Day 52 (
graphics3d): 3D graphics. Meshes, coordinate spaces and projection, From triangles to shaded pixels, How graphics cards store colour, Seeing voxels: projections and volume rendering. - Day 53 (
multiview): Geometry from multiple images. The pinhole camera and calibration, Two views: epipolar geometry, triangulation, Stereo: from disparity to depth, Structure from motion and bundle adjustment. - Day 54 (
raytracing): Ray tracing. Rays from the camera, and where they hit, Shadows, mirrors and glass, Tracing fast: boxes, trees and grids, Path tracing: Monte Carlo and noise. - Day 55 (
gpus): How GPUs work. Many simple cores: throughput, warps and divergence, Memory is the bottleneck, Data-parallel patterns, What GPUs are good and bad at.