---
title: "Imaging lab: beam hardening, back-projection, echoes and MRI contrast"
heading: How a two-energy X-ray beam hardens with depth, reconstructing a disk from its projections by filtered back-projection, echo levels from a stack of tissue layers, and the echo time that maximizes the contrast between two tissues
eyebrow: S15 · Lesson 42 · Imaging lab
xp: 60
---

::: hook
Lessons 37 to 41 explained how each imaging method forms its contrast. Every scanner then runs computations that turn measurements into a picture: correcting for a beam whose spectrum changes as it passes through the body, reconstructing a slice from its projections, predicting how strong each echo will be, and choosing timings that make one tissue stand out from another. In this lab you'll write a small version of each and check it against what the physics predicts.
:::

::: play
- Two tissues have T2 relaxation times on the sliders. The curve is the difference of their spin-echo signals, $e^{-TE/T_{2a}} - e^{-TE/T_{2b}}$, against echo time (equal proton density and full T1 recovery).
- At short TE both signals are near 1 and the difference is small; at long TE both have decayed.
- The difference peaks between the two T2 values, at $TE^* = \ln(T_{2a}/T_{2b})/(1/T_{2b} - 1/T_{2a})$.
:::

```sim plot
view: graph
x: E = 0..400
y: d = 0..0.6
slider: a = 50..300 = 100
slider: b = 20..200 = 60
plot: exp(-E/a) - exp(-E/b) | label: signal difference
```

::: predict
## Two tissues have T2 of 100 ms and 60 ms. Which echo time gives the most contrast between them?

- [ ] 0 ms, where the signals are strongest
- [ ] 60 ms
- [x] About 77 ms
- [ ] 100 ms

::: reveal
Setting the derivative of $e^{-TE/100} - e^{-TE/60}$ to zero gives $TE^* = \ln(100/60)/(1/60 - 1/100)$ = 76.6 ms, where the difference is 0.186. Longer echoes lose signal faster than they gain contrast; task 4 finds the optimum numerically too.
:::
:::

::: nameit
## What the lab computes

- **Beam hardening**: a beam of two equal-weight energies with attenuation coefficients $\mu_1 > \mu_2$ transmits $(e^{-\mu_1x} + e^{-\mu_2x})/2$ through thickness x, and its effective coefficient $-\ln T/x$ falls with x as the low-energy part is filtered out. Uncorrected, this makes the center of a uniform object look less dense than its edge (cupping).
- **Filtered back-projection**: for parallel projections p(s) over angles from 0 to π, convolve each with the discrete ramp filter ($h_0 = 1/4d^2$, $h_n = -1/(n\pi d)^2$ for odd n, 0 for even n), then add each filtered projection back along its lines, $f(x, y) = \frac\pi{N_\theta}\sum_\theta q(x\cos\theta + y\sin\theta)$, interpolating linearly between samples. A uniform disk of radius R and attenuation μ has projections $2\mu\sqrt{R^2 - s^2}$.
- **Echoes**: through layers of impedance $Z_i$ and thickness $d_i$, the echo from each interface has intensity $R_iT_\text{path}^2$ times the attenuation $10^{-\alpha f\cdot2d/10}$, where R is the intensity reflection coefficient $((Z_2 - Z_1)/(Z_2 + Z_1))^2$, $T_\text{path}$ the product of $(1 - R)$ over the interfaces passed, and α in dB/(cm·MHz).
- **MRI contrast**: spin-echo signal $\rho(1 - e^{-TR/T_1})e^{-TE/T_2}$, and the TE that maximizes the difference between two tissues' T2 decays.
:::

::: check
kind: python

## Write `transmit(mu1, mu2, x)` returning (transmitted fraction, effective attenuation coefficient) for a two-energy beam.

```python starter
import math

def transmit(mu1, mu2, x):
    mu = (mu1 + mu2) / 2
    return math.exp(-mu * x), mu
```

```python solution
import math

def transmit(mu1, mu2, x):
    T = (math.exp(-mu1 * x) + math.exp(-mu2 * x)) / 2
    return T, -math.log(T) / x
```

```python tests
T1, m1 = transmit(0.3, 0.15, 1)
T20, m20 = transmit(0.3, 0.15, 20)
assert abs(m1 - 0.22219) < 1e-4 and abs(m20 - 0.18223) < 1e-4, "The effective μ falls from 0.222 to 0.182 cm⁻¹."
assert m20 > 0.15, "It approaches the higher energy's coefficient but never reaches it."
```

::: right
Right. Averaging the coefficients, as the starter does, ignores that the beam's spectrum changes along the path.
:::
:::

::: check
kind: python

## Write `fbp_disk(R, mu, N=32, views=60, bins=65)`: reconstruct an N × N image over the square from −1 to 1 from the analytic projections of a centered disk, sampled at `bins` points from −1 to 1.

```python starter
def fbp_disk(R, mu, N=32, views=60, bins=65):
    return [[0.0] * N for _ in range(N)]
```

```python solution
import math

def fbp_disk(R, mu, N=32, views=60, bins=65):
    d = 2.0 / (bins - 1)
    s = [-1 + k * d for k in range(bins)]
    p = [2 * mu * math.sqrt(R * R - x * x) if abs(x) < R else 0.0 for x in s]

    def h(n):
        if n == 0:
            return 1 / (4 * d * d)
        return 0.0 if n % 2 == 0 else -1 / (n * n * math.pi ** 2 * d * d)

    q = [d * sum(p[j] * h(i - j) for j in range(bins)) for i in range(bins)]
    img = [[0.0] * N for _ in range(N)]
    for v in range(views):
        th = math.pi * v / views
        c, sn = math.cos(th), math.sin(th)
        for iy in range(N):
            y = -1 + (iy + 0.5) * 2 / N
            for ix in range(N):
                x = -1 + (ix + 0.5) * 2 / N
                u = (x * c + y * sn + 1) / d
                k = int(math.floor(u))
                fr = u - k
                if 0 <= k < bins - 1:
                    img[iy][ix] += q[k] * (1 - fr) + q[k + 1] * fr
    return [[val * math.pi / views for val in row] for row in img]
```

```python tests
img = fbp_disk(0.5, 1.0)
N = 32
inside = [img[i][j] for i in range(N) for j in range(N) if (-1 + (i + 0.5) / 16) ** 2 + (-1 + (j + 0.5) / 16) ** 2 < 0.16]
outside = [img[i][j] for i in range(N) for j in range(N) if 0.4 < (-1 + (i + 0.5) / 16) ** 2 + (-1 + (j + 0.5) / 16) ** 2 < 0.8]
assert abs(sum(inside) / len(inside) - 1) < 0.02, "Inside the disk the reconstruction is within 2% of μ = 1."
assert max(abs(v) for v in outside) < 0.08, "Outside the disk, within the scanned circle, it's near zero."
```

::: right
Right. Without the ramp filter, back-projection alone would smear the disk into a blur falling off as 1/r.
:::
:::

::: check
kind: python

## Write `echoes(layers, f, alpha=0.5)`: for a list of (impedance in MRayl, thickness in cm) layers, return the echo level in dB from each interface, relative to the transmitted pulse.

```python starter
import math

def echoes(layers, f, alpha=0.5):
    out = []
    for i in range(len(layers) - 1):
        Z1, Z2 = layers[i][0], layers[i + 1][0]
        out.append(10 * math.log10(((Z2 - Z1) / (Z2 + Z1)) ** 2))
    return out
```

```python solution
import math

def echoes(layers, f, alpha=0.5):
    out = []
    T = 1.0
    depth = 0.0
    for i in range(len(layers) - 1):
        Z1, d = layers[i]
        Z2 = layers[i + 1][0]
        depth += d
        R = ((Z2 - Z1) / (Z2 + Z1)) ** 2
        out.append(10 * math.log10(R * T * T) - alpha * f * 2 * depth)
        T *= 1 - R
    return out
```

```python tests
e = echoes([(1.63, 1.0), (1.38, 1.5), (1.70, 3.0), (7.8, 1.0)], 5)
assert abs(e[0] + 26.61) < 0.02 and abs(e[1] + 32.23) < 0.02 and abs(e[2] + 31.50) < 0.02, "Skin–fat, fat–muscle and muscle–bone echoes: −26.6, −32.2 and −31.5 dB."
deep = echoes([(1.70, 10.0), (7.8, 1.0)], 5)[0]
assert deep < e[2], "Bone reflects strongly, but 10 cm of muscle costs 50 dB on the way out and back."
```

::: right
Right. Depth costs more than impedance contrast gains, which is why scanners apply gain that rises with time after each pulse.
:::
:::

::: check
kind: python

## Write `spin_echo(pd, t1, t2, tr, te)` and `best_te(t2a, t2b)`, the echo time that maximizes the difference between two tissues' T2 decays.

```python starter
import math

def spin_echo(pd, t1, t2, tr, te):
    return pd

def best_te(t2a, t2b):
    return (t2a + t2b) / 2
```

```python solution
import math

def spin_echo(pd, t1, t2, tr, te):
    return pd * (1 - math.exp(-tr / t1)) * math.exp(-te / t2)

def best_te(t2a, t2b):
    return math.log(t2a / t2b) / (1 / t2b - 1 / t2a)
```

```python tests
import math
te = best_te(100, 60)
assert abs(te - 76.624) < 0.01, "T2 of 100 and 60 ms: TE* = 76.6 ms."
diff = lambda x: spin_echo(1, 900, 100, 1e9, x) - spin_echo(1, 900, 60, 1e9, x)
assert all(diff(te) >= diff(x) - 1e-12 for x in range(0, 400)), "No other echo time does better."
assert abs(spin_echo(1, 900, 100, 500, 15) - 0.3672) < 1e-3, "A T1-weighted scan (TR 500, TE 15) keeps 37% for T1 = 900 ms."
```

::: right
Right. Each contrast has its best timing, which is why protocols are tuned for the tissues they must separate.
:::
:::

::: explain
## Why must CT projections be filtered before they are back-projected?

::: model
Back-projection smears each projection value back along the line it was measured on, so every point in the object contributes not only to its own location but to every location along all the lines through it. Summed over angles, a single point becomes a blur that falls off as one over the distance from it, which in frequency terms means the image's spectrum is weighted by 1/|frequency|: fine detail is suppressed and low frequencies piled up. Multiplying each projection's spectrum by |frequency| first, the ramp filter, cancels that weighting exactly, so the back-projected sum reproduces the object. In practice the ramp is rolled off at high frequencies to limit noise.
:::
:::
