ECE 63700: Digital Image Processing I

Lab 3: Image Filtering

Overview What the lab is about, the data, and the ground rules.

What This Lab Is About

Due: Friday, Jan. 29, 2027.

In this laboratory, you will filter full color images using both FIR and IIR filters: a low pass filter, a sharpening filter known as an unsharp mask, and an IIR filter specified by a 2-D difference equation. For each filter you derive the frequency response, plot it, apply the filter, and check your code against the FFT.

You direct Claude, or another agentic AI, to write the PyTorch code from the specification on this page. You run the experiments and explain the results. You are graded on your specification, your checks, and your reading of the results.

The Data

Download lab3-data.zip. It holds two 8-bit RGB PNG images.

  • img03.png, 512 pixels wide and 768 pixels tall, 621 KB.
  • imgblur.png, a blurred img03.png, the same size, 433 KB.
wget https://charlesbouman.org/ece63700/labs/lab3-data.zip
unzip lab3-data.zip

Ground Rules

  • All filtering code is in PyTorch, in one file, lab3.py, run in the labs conda environment from Lab 2. NumPy and matplotlib are allowed for plotting.
  • lab3.py holds only functions. Run experiments from a separate script that imports it.
  • Use the exact signatures on this page, each with a short docstring.
  • Divide each image by 255 to scale it to \([0,1]\). Use float64.
  • A color image is a \((3, H, W)\) tensor. Filter each channel separately.
  • \(m\) counts rows from the top. \(n\) counts columns from the left.
  • All filters use free boundary conditions: pixels indexed outside the image are considered equal to zero.
  • Filtering will sometimes cause a pixel to exceed 1 or go below 0. Clip the pixel's value to \([0,1]\) before displaying or exporting the image, and not before.
  • No Python for loop over pixels, except in iir_direct (Step 8).
Run the checks in Steps 3, 5, 8, and 9 before you look at any filtered image. A filter with a mistake often still produces a plausible picture.
Parameters for the Experiments The settings for every hand-in item, in one place.

Parameters for Every Experiment

ItemExperimentInputFilter and settings
D1Low-pass response (Step 2) —9 by 9 average, plot over \([-\pi,\pi]^2\)
D2FIR checks (Step 3) 21 by 21 impulse at \((10,10)\) 9 by 9 average and a 3 by 3 test kernel; FFT size 256
D3Low-pass filtering (Step 4) img03.png9 by 9 average
D4Unsharp mask responses (Step 5) —5 by 5 average; \(\lambda = 1.5\); FFT size 256
D5Sharpening (Step 6) imgblur.png\(\lambda = 0.2,\ 0.8,\ 1.5\)
D6IIR response (Step 7) —equation (6), plot over \([-\pi,\pi]^2\)
D7Point spread function (Step 8) 256 by 256 impulse at \((127,127)\)equation (6), displayed as \(100\,h\); FFT size 256
D8IIR filtering (Step 8) img03.pngequation (6)
D9Separable form and timing (Step 9) impulse of D7 and img03.pngequation (6), both implementations
Module 1: An FIR Low-Pass Filter Steps 1 to 4. Set up the code, derive the frequency response, build an FIR filter, and check it.

Step 1: Set Up lab3.py

Copy these helpers into lab3.py.

import numpy as np
import torch
import torch.nn.functional as F
from PIL import Image


def load_image(path):
    """Read an 8-bit image file as a (C, H, W) float64 tensor in [0, 1]."""
    a = np.asarray(Image.open(path), dtype=np.float64) / 255.0
    if a.ndim == 2:
        a = a[:, :, None]
    return torch.from_numpy(a).permute(2, 0, 1).contiguous()


def save_image(x, path):
    """Clip a (C, H, W) tensor, C = 1 or 3, to [0, 1] and save it as an 8-bit PNG."""
    a = (x.clamp(0.0, 1.0) * 255.0).round().to(torch.uint8)
    a = a.permute(1, 2, 0).numpy()
    if a.shape[2] == 1:
        a = a[:, :, 0]
    Image.fromarray(a).save(path)


def box_kernel(p):
    """Return the (2p+1) by (2p+1) averaging kernel, every entry 1 / (2p+1)^2."""
    k = 2 * p + 1
    return torch.full((k, k), 1.0 / k**2, dtype=torch.float64)


def freq_grid(n):
    """Return n by n grids mu (down rows) and nu (across columns) in [-pi, pi)."""
    w = 2 * torch.pi * (torch.arange(n, dtype=torch.float64) - n // 2) / n
    return torch.meshgrid(w, w, indexing="ij")


def fft_magnitude(h, n):
    """Return |FFT| of h zero padded to n by n, centered to match freq_grid(n)."""
    return torch.fft.fftshift(torch.fft.fft2(h, s=(n, n))).abs()

Step 2: The Frequency Response

In this problem, you will analyze and implement a simple low pass filter given by the \(9 \times 9\) point spread function

$$ h(m,n) = \left\{ \begin{array}{ll} 1/81 & \mbox{for } |m| \le 4 \mbox{ and } |n| \le 4 \\ 0 & \mbox{otherwise} \ . \end{array} \right. \tag{1} $$

The DSFT of \(h(m,n)\) is

$$ H(e^{j\mu}, e^{j\nu}) = \sum_{m=-\infty}^{\infty} \sum_{n=-\infty}^{\infty} h(m,n) \, e^{-j(\mu m + \nu n)} \ , \tag{2} $$

where \(\mu\) goes with \(m\) and \(\nu\) with \(n\), in radians per sample.

Task 2a. Calculate an analytical expression for \(H(e^{j\mu}, e^{j\nu})\), the DSFT of \(h(m,n)\) in (1). It is a real function of \(\mu\) and \(\nu\). State its value at \(\mu = \nu = 0\).

Task 2b. Write box_response to evaluate your answer for box_kernel(p). The filter (1) is \(p = 4\). Where the formula gives zero divided by zero, return the correct limit.

def box_response(mu, nu, p):
    """Return the real H(e^{j mu}, e^{j nu}) of box_kernel(p), shaped like mu and nu."""

Task 2c. Plot the magnitude of the frequency response \(|H(e^{j\mu}, e^{j\nu})|\) on freq_grid, as a surface or an image with a colorbar. Make sure to label the axes properly and plot over the region \([-\pi,\pi] \times [-\pi,\pi]\).

HAND IN · D1

Your derivation of \(H\) for (1), its value at \(\mu = \nu = 0\), and the plot of \(|H|\).

Step 3: The FIR Filter and Its Checks

An FIR filter computes the 2-D convolution

$$ y(m,n) = \sum_{k} \sum_{l} h(k,l) \, x(m-k, n-l) \ , \tag{3} $$

with \(x = 0\) outside the image. Store \(h\) as an odd-size \(K \times L\) array with \(h(0,0)\) at h[K//2, L//2].

def fir_filter(x, h):
    """Return the convolution (3) of each channel of x (C, H, W) with h (K, L), K and L odd."""
  • Zero padding. The output has the same shape as the input.
  • One call to torch.nn.functional.conv2d, with the channels as the batch. No loop over pixels.
conv2d computes correlation, not convolution. Flip the kernel in both axes first. The symmetric kernels in this lab hide this mistake, and h_test below catches it.

Task 3a. The impulse check. Filter a \(1 \times 21 \times 21\) image that is 1 at \((10,10)\) and 0 elsewhere with box_kernel(4). Report the largest absolute difference from the kernel placed at the center of a \(21 \times 21\) array of zeros. Repeat with this nonsymmetric kernel:

h_test = torch.arange(1, 10, dtype=torch.float64).reshape(3, 3)

Task 3b. The FFT check. The DFT of \(h\) zero padded to \(N \times N\) equals the DSFT (2) at \(\mu = 2\pi k/N\), \(\nu = 2\pi l/N\), up to a phase. Compute and report

mu, nu = freq_grid(256)
fft_err = (fft_magnitude(box_kernel(4), 256)
           - box_response(mu, nu, 4).abs()).abs().max()
Pass criterion. All three errors are at the level of round-off. If only h_test fails, the kernel is not flipped. A shift of one pixel means the padding is wrong. If the FFT check fails, look at Task 2a and the limit at zero frequency.
HAND IN · D2

The two impulse check errors (box kernel and h_test) and the FFT check error.

Step 4: Filter the Image

Filter the red, green, and blue components of img03.png with box_kernel(4) and generate a full color output image. Show input and output side by side at the same size.

HAND IN · D3

img03.png and the filtered image, with one sentence on what happened near the borders, and why.

Module 2: The Unsharp Mask Steps 5 and 6. Derive the response of a sharpening filter and apply it to a blurred image.

Step 5: The Frequency Response of the Unsharp Mask

In this problem, you will analyze the effect of a sharpening filter known as an unsharp mask. The terminology comes from the fact that an unsharp mask filter removes the unsharp (low frequency) component of the image, and therefore produces an image with a sharper appearance.

Let \(h(m,n)\) be a low pass filter. For our purposes use box_kernel(2):

$$ h(m,n) = \left\{ \begin{array}{ll} 1/25 & \mbox{for } |m| \le 2 \mbox{ and } |n| \le 2 \\ 0 & \mbox{otherwise} \ . \end{array} \right. \tag{4} $$

The unsharp mask filter is then given by

$$ g(m,n) = \delta(m,n) + \lambda \big( \delta(m,n) - h(m,n) \big) \ , \tag{5} $$

where \(\delta(m,n)\) is 1 at \((0,0)\) and 0 elsewhere, and \(\lambda\) is a constant greater than zero.

Task 5a. Calculate analytical expressions for \(H(e^{j\mu}, e^{j\nu})\), the DSFT of \(h(m,n)\) in (4), and for \(G(e^{j\mu}, e^{j\nu})\), the DSFT of \(g(m,n)\).

Task 5b. Write these two functions.

def unsharp_kernel(lam):
    """Return the 5 by 5 float64 kernel g of (5), with g(0, 0) at the center."""


def unsharp_response(mu, nu, lam):
    """Return the real G(e^{j mu}, e^{j nu}) of (5), shaped like mu and nu."""

Task 5c. Plot \(|H|\) for (4) and \(|G|\) for \(\lambda = 1.5\) over \([-\pi,\pi]^2\), labeled as in Step 2. Run the FFT check of Task 3b on \(g\) with \(\lambda = 1.5\), using unsharp_kernel and unsharp_response. Report the largest \(|G|\) on the grid.

HAND IN · D4

Your derivations of \(H\) and \(G\), the plots of \(|H|\) and of \(|G|\) for \(\lambda = 1.5\), the FFT check error for \(g\), and the largest value of \(|G|\).

Step 6: Sharpen the Blurred Image

Apply your sharpening filter to imgblur.png for \(\lambda = 0.2\), \(0.8\), and \(1.5\), and compare each result to the original image. Show all four at the same size, and the same small region of all four, for example \(200 \times 200\) around the eyes. For each output, report the percentage of values outside \([0,1]\) before clipping.

HAND IN · D5

The input, the three sharpened images, the four close-ups, and the three clipping percentages. In two or three sentences: what improves as \(\lambda\) grows, and what gets worse?

Module 3: An IIR Filter Steps 7 to 11. Derive the response, compute the point spread function, compare a pixel loop with a separable form, and answer the questions.

Step 7: The Frequency Response of the IIR Filter

In this problem, you will analyze the effect of an IIR filter specified by a 2-D difference equation. Let \(h(m,n)\) be the impulse response of an IIR filter with corresponding difference equation

$$ y(m,n) = 0.01\, x(m,n) + 0.9 \big( y(m-1,n) + y(m,n-1) \big) - 0.81\, y(m-1,n-1) \ , \tag{6} $$

where \(x(m,n)\) is the input and \(y(m,n)\) is the output. Both are zero outside the image, so the recursion starts from \(y = 0\) at the top left corner.

Task 7a. Take the 2-D Z-transform of (6) and derive \(H(z_1, z_2) = Y(z_1,z_2) / X(z_1,z_2)\), with \(z_1\) for \(m\) and \(z_2\) for \(n\). Set \(z_1 = e^{j\mu}\), \(z_2 = e^{j\nu}\) to get \(H(e^{j\mu}, e^{j\nu})\).

Task 7b. Show that the denominator factors:

$$ 1 - 0.9 z_1^{-1} - 0.9 z_2^{-1} + 0.81 z_1^{-1} z_2^{-1} = \big( 1 - 0.9 z_1^{-1} \big) \big( 1 - 0.9 z_2^{-1} \big) \ . \tag{7} $$

Use (7) to find \(h(m,n)\) in closed form and the gain at zero frequency, \(H(e^{j0}, e^{j0})\).

Task 7c. Write iir_response and plot \(|H|\) over \([-\pi,\pi]^2\), labeled as in Step 2.

def iir_response(mu, nu):
    """Return H(e^{j mu}, e^{j nu}) of (6), a complex128 tensor shaped like mu and nu."""
HAND IN · D6

Your derivation of \(H\), the factorization (7), the closed form for \(h(m,n)\), the gain at zero frequency, and the plot of \(|H|\).

Step 8: The Direct Recursion and the Point Spread Function

iir_direct computes (6) by visiting pixels in raster order: row by row from the top, left to right in each row. It is the one function that loops over pixels.

def iir_direct(x):
    """Apply (6) to x (C, H, W) with a raster-order pixel loop, zero outside the image."""
Reading a PyTorch tensor one element at a time is slow. The loop may work on a NumPy copy. It should finish on img03.png in well under a minute.

Task 8a. The point spread function. Compute the point spread function of the filter, \(h(m,n)\), by applying iir_direct to a \(256 \times 256\) image of the form \(x(m,n) = \delta(m-127, n-127)\). The output is \(h(m-127, n-127)\), with largest value 0.01. Display and save \(100\,h\), clipped to \([0,1]\), in grayscale with a colorbar and labeled axes. Report the sum of the output, and compare it with your closed form from Task 7b.

Task 8b. The FFT check. Run the check of Task 3b with this point spread function and iir_response. The error is small but not at round-off (Question 4).

HAND IN · D7

The image of \(100\,h\), the sum of the point spread function, and the FFT check error.

Task 8c. Filter the red, green, and blue components of img03.png with iir_direct and generate a full color output image.

HAND IN · D8

The filtered image, next to img03.png.

Step 9: The Separable Form

By (7), the filter is a recursion down each column,

$$ u(m,n) = x(m,n) + 0.9\, u(m-1,n) \ , \tag{8} $$

followed by a recursion along each row,

$$ y(m,n) = 0.01\, u(m,n) + 0.9\, y(m,n-1) \ . \tag{9} $$

Each step of (8) computes a whole row of \(u\), for all columns and channels. Each step of (9) computes a whole column of \(y\). That is \(H + W\) loop steps, against \(3HW\) for the direct form. Row and column loops are allowed. A loop over pixels is not.

def iir_separable(x):
    """Apply (6) to x (C, H, W) as recursions (8) and (9), one row or column per step."""

Task 9a. Check that the two forms agree. Report the largest absolute difference between iir_direct and iir_separable on the impulse of Task 8a and on img03.png. Both should be at round-off.

Task 9b. Time them. Time each on img03.png with time.perf_counter(). For the separable form, report the shortest of a few runs. Report both times and the speedup (direct time divided by separable time).

HAND IN · D9

The two differences, the two times, the speedup, and one sentence on how your iir_direct loop indexes the image (tensor, NumPy array, or Python list).

Step 10: Your Specification

You directed the AI to write seven functions: box_response, fir_filter, unsharp_kernel, unsharp_response, iir_response, iir_direct, and iir_separable.

HAND IN · D10

Your specification, quoted. If you corrected it during the build, show the correction and say what was wrong.

Step 11: Questions to Answer

Answer each in a few sentences. Cite the figure or number you use.

  1. Use your plot of \(|G|\) to explain why the unsharp mask makes noise more visible. For white noise input with variance \(\sigma^2\), the output variance is \(\sigma^2 \sum_{m,n} g(m,n)^2\). Compute this factor for \(\lambda = 1.5\).
  2. What is \(G(e^{j0}, e^{j0})\), and why does it not depend on \(\lambda\)? What happens to \(|G|\) at high frequencies as \(\lambda\) grows? Relate this to the clipping percentages in D5.
  3. Show that the IIR filter (6) is stable by computing \(\sum_{m,n} |h(m,n)|\). What is its gain at zero frequency, and how does the sum in D7 confirm it?
  4. Why does the FFT check of Task 8b not reach round-off, while that of Task 3b does? Estimate the error from your closed form for \(h(m,n)\).
  5. The point spread function is zero above and to the left of the impulse. What does that do to an edge in D8? Describe how to use iir_separable to build a smoothing filter whose point spread function is symmetric about its center.
HAND IN · D11

Your answers to the five questions.

Deliverables What to submit, and where each item comes from.

What to Hand In

Submit two files through Brightspace.

  1. A report, as a single PDF, labeled "Lab 3", with the items below in this order.
  2. Your lab3.py, as a plain .py file. No code in the report and no zip file.

Also commit and push your code to your image-processing-labs repository under lab3 before you submit.

  1. Your name and the link to your GitHub repository.
  2. D1 \(H\) for the \(9 \times 9\) average, its value at zero frequency, and the plot of \(|H|\).
  3. D2 The two impulse check errors and the FFT check error.
  4. D3 img03.png, the low-pass image, and the sentence on the borders.
  5. D4 \(H\) and \(G\), the plots of \(|H|\) and \(|G|\), the FFT check error for \(g\), and the largest \(|G|\).
  6. D5 imgblur.png, the three sharpened images, the four close-ups, the clipping percentages, and your comparison.
  7. D6 \(H\) for the IIR filter, the factorization, \(h\), the gain at zero frequency, and the plot of \(|H|\).
  8. D7 The image of \(100\,h\), its sum, and the FFT check error.
  9. D8 The IIR filtered image next to img03.png.
  10. D9 The two differences, the two times, the speedup, and how your loop indexes the image.
  11. D10 Your specification, quoted, with any corrections.
  12. D11 Your answers to the five questions.

Concise and clear beats long.