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.
Download lab3-data.zip. It holds two 8-bit RGB PNG images.
img03.png, the same size, 433 KB.wget https://charlesbouman.org/ece63700/labs/lab3-data.zip unzip lab3-data.zip
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.float64.for loop over pixels, except in
iir_direct (Step 8).| Item | Experiment | Input | Filter and settings |
|---|---|---|---|
| D1 | Low-pass response (Step 2) | — | 9 by 9 average, plot over \([-\pi,\pi]^2\) |
| D2 | FIR checks (Step 3) | 21 by 21 impulse at \((10,10)\) | 9 by 9 average and a 3 by 3 test kernel; FFT size 256 |
| D3 | Low-pass filtering (Step 4) | img03.png | 9 by 9 average |
| D4 | Unsharp mask responses (Step 5) | — | 5 by 5 average; \(\lambda = 1.5\); FFT size 256 |
| D5 | Sharpening (Step 6) | imgblur.png | \(\lambda = 0.2,\ 0.8,\ 1.5\) |
| D6 | IIR response (Step 7) | — | equation (6), plot over \([-\pi,\pi]^2\) |
| D7 | Point spread function (Step 8) | 256 by 256 impulse at \((127,127)\) | equation (6), displayed as \(100\,h\); FFT size 256 |
| D8 | IIR filtering (Step 8) | img03.png | equation (6) |
| D9 | Separable form and timing (Step 9) | impulse of D7 and img03.png | equation (6), both implementations |
lab3.pyCopy 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()
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]\).
Your derivation of \(H\) for (1), its value at \(\mu = \nu = 0\), and the plot of \(|H|\).
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."""
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()
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.
The two impulse check errors (box kernel and h_test)
and the FFT check error.
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.
img03.png and the filtered image, with one sentence on
what happened near the borders, and why.
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):
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.
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|\).
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.
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?
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."""
Your derivation of \(H\), the factorization (7), the closed form for \(h(m,n)\), the gain at zero frequency, and the plot of \(|H|\).
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."""
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).
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.
The filtered image, next to img03.png.
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).
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).
You directed the AI to write seven functions:
box_response, fir_filter,
unsharp_kernel, unsharp_response,
iir_response, iir_direct, and
iir_separable.
Your specification, quoted. If you corrected it during the build, show the correction and say what was wrong.
Answer each in a few sentences. Cite the figure or number you use.
iir_separable to build a smoothing filter whose point
spread function is symmetric about its center.Your answers to the five questions.
Submit two files through Brightspace.
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.
img03.png, the low-pass image, and the sentence on
the borders.imgblur.png, the three sharpened images, the four
close-ups, the clipping percentages, and your comparison.img03.png.Concise and clear beats long.