Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 46 ยท Projects

Project: A Small Photo Filter Toolkit

Build blur, sharpen, sepia, vignette and pixelate filters as small composable functions, chain them into pipelines and test them with array assertions.

Photo apps look magical, but most filters are short array programs. A sepia tone is a 3 by 3 matrix multiplication. A vignette is a brightness gradient. A sharpen filter is a blurred copy subtracted from the original. In this project you will write seven of them, make them composable so that they chain into presets such as "vintage", and then do the part many tutorials skip: test them. Image code fails silently (a wrong filter still returns an image), so automated checks on small arrays are the best defence.

The design rule is simple. Every filter is created by a function that takes the settings and returns a function from image to image:

flowchart LR
    A["settings<br/>sigma=2"] --> B["blur(2)"]
    B --> C["a function<br/>image -> image"]
    D["photo"] --> C --> E["new photo"]
    C --> F["pipeline(blur(2), sepia())"]

A filter factory fixes the settings once; the returned function is a plain image transformer that can be chained with any other.

All images are float arrays of shape (H, W, 3) with values from 0 to 1 (see Images as Arrays for why we prefer float for processing). Every filter returns a new array and never modifies its input.

Step 1: The filters

The toolkit has a synthetic landscape photo to practice on (so no files are needed) and seven filters:

  • brightness(delta) adds a constant and clips to the valid range. See Brightness, Contrast and Gamma for the clipping pitfalls.
  • grayscale() weights the channels with 0.299, 0.587 and 0.114, the luma weights from Color Channels and Color Spaces, and repeats the result on all three channels so the image keeps its shape.
  • blur(sigma) is a Gaussian blur from Blurring and Denoising. The sigma for the channel axis is 0, so colors are never mixed.
  • sharpen(amount, sigma) is an unsharp mask: img + amount * (img - blurred). The difference holds the fine detail; adding it back exaggerates edges.
  • sepia() multiplies each pixel's color vector by a fixed 3 by 3 matrix that maps everything onto brown tones.
  • vignette(strength) multiplies by a factor that is 1 in the centre and falls to 1 - strength at the corners.
  • pixelate(block) replaces each block by its mean color. It is the same operation as the anonymizer in Pitfalls, Ethics and Deployment.
Python Seven filters on a landscape

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look at the statistics as well as the pictures. Brightness raises the mean; the vignette lowers it and cannot reach 1; pixelate leaves the mean exactly where it was, because it only averages inside blocks; the blur changes it by almost nothing. Numbers like these are the seeds of the tests in step 3.

Step 2: Pipelines

Because every filter has the same shape (image in, image out), chaining them is a loop. pipeline(f, g, h) returns a new filter that applies f, then g, then h. Since a pipeline is itself an image-to-image function, pipelines can be nested inside other pipelines.

Order matters. A blur before pixelating averages the image smoothly and then averages blocks, while pixelating before blurring leaves blocky edges that the blur then softens. Sepia and vignette would commute if there were no clipping (a matrix and a per-pixel scale can be applied in either order), but bright pixels get clipped at 1 inside the sepia matrix, so the results differ.

Python Presets and the order of filters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The two blur and pixelate orders differ by about 0.02 on average, a clearly visible gap, and the sepia and vignette orders differ by up to 0.16 at the brightest pixels. Name your presets and write the order down; "it looked fine on my test photo" is not documentation.

Tip: A pipeline that keeps colors as float 0 to 1 throughout, and clips only inside the filters that can leave the range, is easy to reason about. Convert from uint8 once at the start and back once at the end.

Step 3: Testing with arrays

How do you know sharpen is right? Eyeballing a few photos catches big bugs only. Better: state properties that must hold for any image and check them on small arrays. This is how image libraries are tested.

Properties that apply to filters in this toolkit:

  • Shape, dtype and range are preserved for every filter and any input.
  • Identity settings do nothing: blur(0), brightness(0), vignette(0), sharpen(0) and pixelate(1) must return the image unchanged.
  • Constant images have no detail, so blur and sharpen must not change them.
  • Inputs are never modified, because a filter that edits its argument in place will quietly corrupt the original.
  • Specific facts: grayscale gives equal channels, pixelate is idempotent and keeps the mean, a vignette is 1 in the centre and darkest in the corners, sharpening increases edge energy and blurring decreases it.
  • Channels stay independent in a blur: a pure red image must stay pure red.

The last property catches a classic bug. If you write ndi.gaussian_filter(img, sigma) on an (H, W, 3) array with a single sigma, SciPy smooths along all three axes, including the color axis, so red bleeds into green and blue. The picture still looks plausible, which is why only a test finds it. The runner below tests the real toolkit, then a deliberately broken blur.

Python A property-test runner

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The real toolkit passes all nine tests. The buggy blur passes eight of them: it still returns a valid float image with the right shape and range, leaves flat images alone and never touches its input. Only test_blur_keeps_channels_separate fails, reporting that a third of the red leaked into the other channels. Shape and range checks alone would have missed the bug, which is why a suite needs tests about meaning as well as format. In a real project these functions would live in a test file for a runner such as pytest:

Python
# test_filters.py (read-only: the same checks in pytest style)
import numpy as np
import pytest
from filters import blur, sharpen, make_photo

@pytest.mark.parametrize("sigma", [0.5, 1, 3])
def test_blur_preserves_flat_images(sigma):
    flat = np.full((16, 16, 3), 0.4)
    assert np.allclose(blur(sigma)(flat), flat)

def test_sharpen_never_leaves_range():
    out = sharpen(3.0)(make_photo())
    assert out.min() >= 0 and out.max() <= 1

Step 4: Handling uint8 images

Real image files load as uint8 (0 to 255). Our float filters would do the wrong thing on them: brightness(0.2) would add 0.2 to a 0-255 value, and a uint8 sum would wrap around. The clean solution is a small adapter that converts to float, runs the filter and converts back, so the filter code stays simple.

Python An adapter for 8-bit images

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Plain uint8 addition wraps values above 255 to small numbers, which turns the brightest sky pixels nearly black. The adapter clips instead, so the count of darkened pixels is zero.

Where to go next

  • More filters: contrast and gamma curves, saturation (work in HSV), edge-enhance with the Sobel operator, a tilt-shift blur whose strength depends on the row, film grain (add noise from a fixed seed).
  • A tiny API: store filter names and settings in a list of dictionaries, so a preset can be saved as text and rebuilt. Save the pipeline description next to the image so you can reproduce it.
  • Speed: the pixelate loop is fine for small images, but a reshape-and-mean trick is far faster on big ones, and blurs can use separable kernels (see Convolution and Correlation). Always measure first.
  • Real photos: with Pillow or OpenCV you load an actual file, call to_float, run the same pipeline and write the result back.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In this toolkit, what does blur(2) return?

    Filters are factories: blur(2) fixes the settings and returns an image-to-image function, which is what lets pipeline() chain any filters in any order.
  2. 2. Why does sharpen compute img + amount * (img - blurred)?

    This is the unsharp mask. The blurred copy holds the smooth part of the image, so the difference isolates edges and texture.
  3. 3. Why is ndi.gaussian_filter(img, 2) on an (H, W, 3) image a bug?

    With one sigma every axis is smoothed, including the channel axis. Passing sigma=(s, s, 0) keeps the channels independent.
  4. 4. Which test would catch a filter that modifies its input array in place?

    Only comparing the original array with a saved copy after the call can reveal in-place modification; the other checks look at the output.
  5. 5. Why wrap float filters in a uint8 adapter instead of doing arithmetic on uint8 arrays?

    Adding to a uint8 array wraps past 255 back to small values. Converting to float, clipping, and converting back avoids it.

Summary

  • A filter factory returns an image-to-image function, which makes filters composable: pipeline(f, g, h) is itself a filter.
  • Work with float arrays in the range 0 to 1, return new arrays, and clip only where values can leave the range.
  • Blur is a Gaussian with sigma 0 along the color axis, sharpen is an unsharp mask, sepia is a 3 by 3 color matrix, a vignette is a radial brightness factor, and pixelate averages blocks.
  • Order matters when filters clip or are nonlinear. Document presets.
  • Test with properties on small arrays: shape, range, identity settings, flat images, no input mutation and specific facts. A deliberately broken filter shows what the tests catch.
  • Convert real uint8 images with an adapter instead of doing arithmetic on them directly.

That completes the four projects in this chapter. Continue with the last project, Project: Handwritten Digit Recognizer.