ECE 63700: Digital Image Processing I

Lab 4: 2-D Random Processes

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

What This Lab Is About

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.

The Data

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

Ground Rules

  • All code is in PyTorch, in one file, 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.
  • Use the exact signatures on this page, each with a short docstring.
  • Divide the image by 255 to scale it to \([0,1]\). Use float64. A PSD on this scale is \(1/255^2\) times the PSD on the 0 to 255 scale.
  • \(m\) counts rows from the top and goes with frequency \(\mu\). \(n\) counts columns from the left and goes with \(\nu\). Both frequencies are in radians per sample.
  • Make sure that all plots have accurate and clearly labeled axes, and have titles that indicate what is being plotted. Show images in grayscale with a colorbar.
  • No Python for loop over pixels or over blocks, except the row and column loops of iir_separable.
Run the checks in Steps 4, 6, and 8 before you interpret any plot. A PSD estimate with the wrong normalization still produces a plausible surface.
Parameters for the Experiments The settings for every hand-in item, in one place.

Parameters for Every Experiment

ItemExperimentInputEstimate and settings
D1One-block estimates (Step 2) img04g.png spec_anal, centered block of size 64, 128, and 256
D2Averaged 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
D3White 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
D4Theoretical PSD (Step 7) — equation (7) with \(\sigma_x^2 = 1/12\), on freq_grid(64)
D5Estimated PSD and comparison (Step 8) \(y\) from D3 better_spec_anal; compare over all frequencies and over \(|\mu|, |\nu| \ge \pi/8\)
Module 1: Power Spectral Density of an Image Steps 1 to 4. Set up the code, compute one-block estimates, build an averaged estimate, and check it with Parseval's relation.

Step 1: Set Up 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)

Step 2: The One-Block Estimate

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).

HAND IN · D1

img04g.png and the three log PSD plots, for \(N = 64\), \(128\), and \(256\).

Step 3: The Averaged Estimate

Write better_spec_anal(x), which computes a better estimate of the power spectral density of x. It should:

  • Subtract the mean of the \(320 \times 320\) region at the center of x, and cut that region into 25 non-overlapping \(64 \times 64\) blocks \(z_b(m,n)\), \(b = 1, \dots, 25\).
  • Multiply each block by the 2-D separable Hamming window \(w(m,n) = h(m)\, h(n)\), the outer product of torch.hamming_window(64, periodic=False, dtype=torch.float64) with itself.
  • Compute the squared DFT magnitude \(|Z_b(k,l)|^2\) of each windowed block, and average across the 25 blocks:
$$ \hat S(k,l) = \frac{1}{25} \sum_{b=1}^{25} \frac{|Z_b(k,l)|^2}{\sum_{m,n} w(m,n)^2} \ . \tag{3} $$

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.

Step 4: The Parseval Check

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.

Pass criterion. The relative error is at round-off. An error by a factor of \(64^2\) means the DFT normalization is wrong. Another constant factor means the estimate and the check use different window sums. The two variances differ, because the window weights the center of each block most.
HAND IN · D2

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.

Module 2: Power Spectral Density of a 2-D AR Process Steps 5 to 10. Generate white noise, filter it, derive the PSD by hand, compare it with your estimate, and answer the questions.

Step 5: White Noise

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\).

Step 6: The AR Process

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]\).

HAND IN · D3

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.

Step 7: The Theoretical PSD

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."""
HAND IN · D4

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\).

Step 8: Estimate the PSD and Compare

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\).

Pass criterion. Away from the axes, the mean ratio is within about 10 percent of 1. Over all frequencies the agreement is worse, because \(S_y\) has a very narrow peak at zero frequency (Question 4).

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).

HAND IN · D5

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.

Step 9: Your Specification

You directed the AI to write three functions: better_spec_anal, iir_separable, and ar_psd.

HAND IN · D6

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

Step 10: Questions to Answer

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

  1. Why does a larger block in D1 not reduce the fluctuation of the estimate at each frequency? What does it change?
  2. Averaging \(K\) independent one-block estimates divides the variance at each frequency by \(K\). By what factor does it divide the standard deviation for \(K = 25\)? For small errors, the standard deviation of \(\log \hat S\) is about \(1/\sqrt{K}\). Compare this with the RMS log difference in D5.
  3. What does the Hamming window change, compared with no window, in leakage (power from strong frequencies that appears at weak ones) and in frequency resolution? Run (3) on \(y\) with \(w = 1\), report the mean ratio over the second set of D5, and explain the difference.
  4. Why is \(S_y\) concentrated at low frequencies? What does \(a = 0.99\) do to the height and width of the peak at zero frequency, and to the appearance of \(y\) in D3? Use this to explain why the estimate disagrees with the theory near \(\mu = 0\) and \(\nu = 0\), where the frequency spacing is \(2\pi/64\).
  5. Use \(h(m,n)\) from Task 6c to show that the variance of \(y(m,n)\) is \(\big(1 - a^{2(m+1)}\big)\big(1 - a^{2(n+1)}\big)\) times its steady state value. Evaluate this at \((96, 96)\) and \((256, 256)\). Will the startup transient change D5 by much?
HAND IN · D7

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 4", with the items below in this order.
  2. Your 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.

  1. Your name and the link to your GitHub repository.
  2. D1 img04g.png and the three one-block log PSD plots.
  3. D2 The log of the averaged estimate, the two sides of the Parseval check, the relative error, and the sample variance.
  4. D3 \(x + 0.5\), the difference equation and factorization, the impulse check error, \(y/255 + 0.5\), and the clipped percentage.
  5. D4 The derivations of \(\sigma_x^2\) and \(S_y\), \(S_y\) at \((0,0)\) and \((\pi,\pi)\), and the plot of \(\log S_y\).
  6. D5 The log of the estimated PSD of \(y\) and the comparison table.
  7. D6 Your specification, quoted, with any corrections.
  8. D7 Your answers to the five questions.

Concise and clear beats long.