Due: Friday, Feb. 5, 2027.
This laboratory explores the use of 2-D random process models for images. Module 1 estimates the power spectral density (PSD) of an image. Module 2 generates a 2-D autoregressive (AR) process and compares its estimated PSD with the theory.
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 lab4-data.zip. It holds img04g.png, an
8-bit grayscale PNG image 768 pixels wide and 512 pixels tall, 268 KB.
Module 2 needs no data file.
wget https://charlesbouman.org/ece63700/labs/lab4-data.zip unzip lab4-data.zip
lab4.py,
run in the labs conda environment from Lab 2. NumPy
and matplotlib are allowed for plotting.lab4.py holds only functions. Run experiments from a
separate script that imports it.float64. A PSD on this scale is \(1/255^2\) times
the PSD on the 0 to 255 scale.for loop over pixels or over blocks, except
the row and column loops of iir_separable.| Item | Experiment | Input | Estimate and settings |
|---|---|---|---|
| D1 | One-block estimates (Step 2) | img04g.png |
spec_anal, centered block of size 64, 128, and 256 |
| D2 | Averaged estimate and Parseval check (Steps 3 and 4) | img04g.png |
better_spec_anal: 25 blocks of 64 by 64 from the
center 320 by 320 region, Hamming window |
| D3 | White noise and the AR process (Steps 5 and 6) | 512 by 512, uniform on \([-0.5, 0.5]\), seed 0 | iir_separable with \(a = 0.99\) and gain 3;
impulse check on a 64 by 64 image |
| D4 | Theoretical PSD (Step 7) | — | equation (7) with \(\sigma_x^2 = 1/12\), on freq_grid(64) |
| D5 | Estimated PSD and comparison (Step 8) | \(y\) from D3 | better_spec_anal; compare over all frequencies and
over \(|\mu|, |\nu| \ge \pi/8\) |
lab4.py
Copy these helpers into lab4.py. For the grayscale image,
load_image returns shape \((1, H, W)\). The PSD functions
take shape \((H, W)\), so pass them x[0].
import numpy as np
import torch
from PIL import Image
import matplotlib.pyplot as plt
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 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 spec_anal(x, n):
"""Return the log of |DFT|^2 / n^2 of the centered n by n block of x (H, W), centered."""
H, W = x.shape
i, j = (H - n) // 2, (W - n) // 2
z = x[i:i + n, j:j + n]
s = torch.fft.fft2(z).abs() ** 2 / n**2
return torch.log(torch.fft.fftshift(s))
def plot_log_psd(log_s, title, path):
"""Save a surface plot of an (n, n) log PSD, centered to match freq_grid(n)."""
mu, nu = freq_grid(log_s.shape[0])
fig = plt.figure(figsize=(6, 4.8))
ax = fig.add_subplot(projection="3d")
surf = ax.plot_surface(nu.numpy(), mu.numpy(), log_s.numpy(),
cmap="viridis", linewidth=0, antialiased=True)
ax.set_xlabel(r"$\nu$ (radians/sample)")
ax.set_ylabel(r"$\mu$ (radians/sample)")
ax.set_zlabel("natural log of PSD")
ax.set_title(title)
fig.colorbar(surf, ax=ax, shrink=0.6, pad=0.12)
fig.tight_layout()
fig.savefig(path, dpi=130)
plt.close(fig)
Model the image, after its mean is removed, as a zero-mean wide-sense stationary random process \(X(m,n)\) with autocorrelation \(R(k,l) = E\big[X(m,n) X(m+k, n+l)\big]\). Its power spectral density is
$$ S(e^{j\mu}, e^{j\nu}) = \sum_{k=-\infty}^{\infty} \sum_{l=-\infty}^{\infty} R(k,l) \, e^{-j(\mu k + \nu l)} \ . \tag{1} $$For an \(N \times N\) block \(z(m,n)\) with DFT \(Z(k,l)\), the simplest estimate at \(\mu = 2\pi k/N\), \(\nu = 2\pi l/N\) is
$$ \hat S(k,l) = \frac{1}{N^2} \, |Z(k,l)|^2 \ . \tag{2} $$
spec_anal estimates the power spectral density by
computing the logarithm of (2) over the block at the center of the
image. It does not subtract the block mean, so its value at zero
frequency, \(N^2\) times the squared mean, stands far above the rest.
Task 2a. Display img04g.png.
Task 2b. Run spec_anal for \(N = 64\), \(128\), and
\(256\), and plot each with plot_log_psd. Notice the power
spectrum estimates remain noisy even when the block size is increased
(Question 1).
img04g.png and the three log PSD plots, for \(N = 64\),
\(128\), and \(256\).
Write better_spec_anal(x), which computes a better
estimate of the power spectral density of x. It should:
x, and cut that region into 25 non-overlapping
\(64 \times 64\) blocks \(z_b(m,n)\), \(b = 1, \dots, 25\).torch.hamming_window(64, periodic=False, dtype=torch.float64)
with itself.
The denominator makes the expected value of \(\hat S\) equal to
\(\sigma^2\) at every frequency for white noise of variance
\(\sigma^2\). Cut the blocks with reshape and
permute, and transform all of them with one call to
torch.fft.fft2. Return the estimate itself, not its log.
def better_spec_anal(x):
"""Return the (64, 64) estimate (3) for x (H, W), H, W >= 320, centered to match freq_grid(64)."""
Task 3a. Plot the log of better_spec_anal for
img04g.png. Compare it with D1.
By Parseval's relation, \(\sum_{k,l} |Z_b(k,l)|^2 = N^2 \sum_{m,n} |w(m,n) z_b(m,n)|^2\), so the mean of (3) over all \(64^2\) frequencies is a weighted sample variance of the region:
$$ \frac{1}{64^2} \sum_{k,l} \hat S(k,l) = \frac{1}{25} \sum_{b=1}^{25} \frac{\sum_{m,n} w(m,n)^2 \, z_b(m,n)^2}{\sum_{m,n} w(m,n)^2} \ . \tag{4} $$Task 4a. Compute the right side of (4) from the blocks, without an FFT. Report both sides, the relative error (absolute difference divided by the right side), and the ordinary sample variance of the region.
The plot of the log of the averaged estimate for
img04g.png, the two sides of (4), the relative error,
and the ordinary sample variance of the region.
Generate a \(512 \times 512\) image \(x\) with independent random numbers each uniformly distributed on \([-0.5, 0.5]\). Use exactly these lines:
g = torch.Generator().manual_seed(0) x = torch.rand(512, 512, generator=g, dtype=torch.float64) - 0.5
Task 5a. Display \(x + 0.5\).
Filter the image \(x\) to produce the image \(y\) using an IIR filter with transfer function
$$ H(z_1, z_2) = \frac{3}{1 - 0.99 z_1^{-1} - 0.99 z_2^{-1} + 0.9801 z_1^{-1} z_2^{-1}} \ , \tag{5} $$where \(z_1\) goes with \(m\) and \(z_2\) with \(n\).
Task 6a. Find the corresponding difference equation. Show that the denominator factors as \(\big(1 - 0.99 z_1^{-1}\big)\big(1 - 0.99 z_2^{-1}\big)\).
Task 6b. Generalize iir_separable from Lab 3 to take
the pole \(a\) and the gain. The first recursion runs down each
column, \(u(m,n) = x(m,n) + a\, u(m-1,n)\). The second runs along each
row, \(y(m,n) = \mbox{gain} \cdot u(m,n) + a\, y(m,n-1)\). Values
outside the image are zero.
def iir_separable(x, a, gain):
"""Apply gain / ((1 - a z1^-1)(1 - a z2^-1)), |a| < 1, to x (C, H, W), one row or column per step."""
Task 6c. The impulse check. The point spread function is \(h(m,n) = \mbox{gain} \cdot a^m a^n\) for \(m, n \ge 0\). Filter a \(1 \times 64 \times 64\) image that is 1 at \((0,0)\) and 0 elsewhere with \(a = 0.99\) and gain 3. Report the largest absolute difference from \(h(m,n)\).
Task 6d. Compute y = iir_separable(x[None], 0.99, 3.0)[0].
Display \(y/255 + 0.5\), which is \(y + 127\) on the 0 to 255 scale,
and report the percentage of displayed values outside \([0,1]\).
The image \(x + 0.5\), the difference equation and the factorization, the impulse check error, the image \(y/255 + 0.5\), and the percentage of clipped values.
White noise of variance \(\sigma_x^2\) filtered by \(H(e^{j\mu}, e^{j\nu})\) has PSD
$$ S_y(e^{j\mu}, e^{j\nu}) = \sigma_x^2 \, \big| H(e^{j\mu}, e^{j\nu}) \big|^2 \ . \tag{6} $$Task 7a. Show that the uniform distribution on \([-0.5, 0.5]\) has variance \(\sigma_x^2 = 1/12\).
Task 7b. Theoretically calculate \(S_y(e^{j\mu}, e^{j\nu})\), the power spectral density of \(y\), as a real function of \(\cos\mu\) and \(\cos\nu\). Call it equation (7). Evaluate it at \((0,0)\) and \((\pi,\pi)\).
Task 7c. Write ar_psd to evaluate (7). Plot
\(\log S_y\) on freq_grid(64) with
plot_log_psd.
def ar_psd(mu, nu, a, gain, var_x):
"""Return S_y of (7) for pole a, gain, and input variance var_x, shaped like mu and nu."""
Your derivation of \(\sigma_x^2\) and of \(S_y\), its values at \((0,0)\) and \((\pi,\pi)\), and the plot of \(\log S_y\).
Task 8a. Use better_spec_anal(y) to estimate the
power spectral density of \(y\), and plot its log.
Task 8b. Compare with the theory. With \(\hat S_y\) the estimate
and \(S_y\) the theory on freq_grid(64), compute the mean
of \(\hat S_y / S_y\) and the mean of \(\log \hat S_y - \log S_y\), over
all \(64^2\) frequencies and over only \(|\mu| \ge \pi/8\) and
\(|\nu| \ge \pi/8\). For the second set, also compute the root mean
square (RMS) of \(\log \hat S_y - \log S_y\).
The recursion starts from zero at the top and left edges, so \(y\) has
a startup transient there. The region used by
better_spec_anal starts 96 pixels from those edges
(Question 5).
The plot of the log of the estimated PSD of \(y\), and a table of the mean ratio and the mean log difference over the two sets of frequencies, with the RMS log difference for the second set.
You directed the AI to write three functions:
better_spec_anal, iir_separable, and
ar_psd.
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.
Your answers to the five questions.
Submit two files through Brightspace.
lab4.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 lab4
before you submit.
img04g.png and the three one-block log PSD plots.Concise and clear beats long.