Algorithmcore
Filtered back-projection
Also called FBP, convolution back-projection.
Reconstruct a CT slice from parallel projections. Convolve each projection with a band-limited ramp kernel, then back-project the filtered projections over all angles.
- Time
- O(a d log d + a n^2) worst
- Space
- O(a d + n^2) extra
- Where
- a = the number of projection angles; d = the number of detector bins; n = the side of the n x n output image
- Model
- Real RAM
- Properties
- deterministicnot in placenot iterativelineariterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- G. N. Ramachandran, A. V. Lakshminarayanan, 1971
Filtered back-projection (FBP) reconstructs a 2D image from its parallel-beam projections, which is the tomographic reconstruction problem. It convolves each projection with a ramp filter and then applies the back-projection operator to the filtered projections. It is a direct discretization of the inversion formula that follows from the Fourier slice theorem. With angles, detector bins and an image it takes time, and it is the standard reconstruction of parallel-beam and fan-beam CT.
In plain words
A CT scanner measures, at each angle, how much the object absorbs along many parallel rays. If you smear each of these profiles back across the image along the direction of its rays and add all the smears, you get a blurred copy of the object. The center of the object gets too much weight, because every smear passes through it.
FBP removes the blur before it smears. It sharpens each profile with a fixed filter. The filter makes the profile go negative just outside each edge. When the smears are added, these negative parts cancel the blur of the other angles, and the true image is left. The filter is the same for each angle, so the method is one short loop: filter each profile, then smear it.
The problem
The data is a sinogram for and . Row samples the projection of an unknown image at the angle . Bin has its center at , with the detector spacing . Here is the Radon transform, with and . The output is an image on the square . Pixel has its center at and , so row 0 is at the top and goes up.
FBP evaluates the inversion formula
where is the filter with the frequency response . With the Fourier transform in ordinary frequency, this formula has no other constant. The proof is on the page of the Radon inversion formula and in the proof below.
The algorithm
FBP(P, τ, n) ▷ P[k][j]: angle θ_k = kπ/a, bin center s_j = (j - (d-1)/2) τ- 1
a, d ← the number of rows and of columns of P - 2
h[m] ← h(mτ) for m = -(d-1) .. d-1 ▷ Ram-Lak or Shepp-Logan kernel - 3
L ← the smallest power of 2 with L ≥ 2d - 1 - 4
Ĥ ← DFT_L(h), with h[m] stored at index m mod L - 5
for k ← 0 to a - 1 do - 6
q_k ← τ · (the first d entries of IDFT_L(DFT_L(P[k] padded with zeros to L) · Ĥ)) - 7
for each pixel (i, j) with center (x_j, y_i) do - 8
f[i][j] ← (π/a) Σ_k LININTERP(q_k, (x_j cos θ_k + y_i sin θ_k)/τ + (d-1)/2) - 9
return f
Line L2 samples the ramp filter cut off at the Nyquist frequency of the detector. The Ram-Lak kernel of Ramachandran and Lakshminarayanan is
The kernel of Shepp and Logan is . Its frequency response is , so it damps the highest frequencies and the noise there. Lines L3 to L6 compute the aperiodic discrete convolution with the fast Fourier transform. The zero padding to makes the circular convolution of the DFT equal to the aperiodic one on the outputs. Line L8 is the discrete back projection: the sum over the angles approximates the integral over , and LININTERP reads the filtered projection between two bin centers by linear interpolation, with 0 outside the detector. The factor is the angle step.
Example
Take the disk of radius with density 1. Its projection is at each angle. With bins and the bin centers are , and
| quantity | values at |
|---|---|
| projection | 0, 0, 0.8660, 1, 0.8660, 0, 0 |
| kernel , | -0.1801, 0, -1.6211, 4, -1.6211, 0, -0.1801 |
| filtered | -0.0450, -0.3900, 0.4607, 0.2980, 0.4607, -0.3900, -0.0450 |
The center value is . The filter makes the values negative just outside the disk, at and . The disk is the same at each angle, so with angles the value at the origin is . The true value is 1. The error comes from the coarse detector: 7 bins of width cannot hold the sharp edge of the disk.
A finer setup gives a smaller error. The table gives the error of the code below on analytic projections with angles, bins, and . These numbers are measurements of this setup, not bounds.
| phantom | Ram-Lak kernel | Shepp-Logan kernel |
|---|---|---|
| Gaussian , largest error | 0.0170 | 0.0239 |
| disk of radius , largest error for | 0.0098 | 0.0093 |
| disk of radius , largest error at the edge | 0.40 | 0.40 |
| Shepp-Logan phantom, value at pixel , true 1.02 | 1.0217 | 1.0206 |
The large error at the edge of the disk is not a fault of the method. A pixel that the edge cuts has no single true value, and the band limit of the detector smooths the jump over about two bins.
Correctness
The proof in proofs/correctness.md has four steps. First, the Fourier slice theorem and polar coordinates in the Fourier plane give for continuous with an integrable Fourier transform. The Jacobian of polar coordinates is the ramp. Second, the Ram-Lak values of line L2 are the samples of the inverse transform of on . Third, if each projection is band-limited to , the discrete sum of line L6 gives the exact samples of the filtered projection, by the sampling theorem. Fourth, with the FFT product of lines L3 to L6 equals that sum, by the convolution theorem. Line L8 is then the trapezoidal rule in for a function of period , plus linear interpolation in . These two steps are the only approximations on band-limited data.
Proof: Correctness of filtered back-projectionfull
We use the conventions of the page. and . The Radon transform is for and . The Fourier transform uses ordinary frequency, . For a fixed angle we write and .
The proof has four parts. Part 1 is the continuous inversion formula that the algorithm discretizes. Part 2 shows that the Ram-Lak kernel of line L2 samples the ramp filter cut off at the Nyquist frequency of the detector. Part 3 shows that, for band-limited projections, the discrete sum of line L6 gives the exact samples of the filtered projection. Part 4 shows that the FFT of lines L3 to L6 computes that sum exactly. The last section names the two approximations that remain, in lines L7 and L8.
Lemma 1 (Fourier slice). Let . Then for each , and for all .
Proof. The map is a rotation, so its Jacobian is 1, and at the point . By Fubini, , and
Theorem 1 (filtered back-projection formula). Let be continuous, with . Put . Then for every
Proof. Because and is continuous, the Fourier inversion formula holds at every point: . Write with and . This map covers once, except for the null set , and . So
The double integral converges absolutely, because its absolute value integrates to . So by Fubini the inner integral exists for almost every . By Lemma 1, , and the inner integral is .
The filter is the ramp. Its inverse transform is not a function, so holds only in the sense of distributions. The algorithm replaces with a band-limited ramp.
Lemma 2 (Ram-Lak kernel). Let , , and . Then , for even , and for odd .
Proof. is even, so . At this is . For with , put . Integration by parts gives
Here , so and . Hence . This is 0 for even and for odd .
Line L2 with the Ram-Lak choice stores exactly these values for .
Lemma 3 (exact discrete filtering). Let be continuous, with for , and with . Then for every integer
Proof. The function on extends to a function of period . Its Fourier coefficients are , by the inversion formula for the band-limited . The coefficients are absolutely summable, so the Fourier series converges uniformly to the continuous periodic extension: for . Put this into the left side. The sum converges uniformly and is bounded on , so the sum and the integral commute:
If also for and , the sum has only the terms . Then lies in for , which is the range that line L2 stores. The sinogram index is the detector position . A shift of the origin by changes neither side, because both sides are convolutions.
Lemma 4 (zero padding). Let . Let for and for . Let for and at the other indices . Let . Then for .
Proof. First, is well defined. Two values in differ by at most , so . By the convolution theorem for the DFT, . For we have , so .
Lines L3 and L4 build and . Line L6 builds , applies the product and multiplies by . The data and the kernel are real, so is real, and taking the real part removes only rounding errors. With Lemmas 2, 3 and 4, line L6 gives exactly, for each projection that is band-limited to and zero outside the detector. If , two kernel samples fall on one index, and the result is a circular convolution with wrong values near both ends.
Back projection (lines L7 to L9). Line L8 makes two approximations of Theorem 1, with replaced by .
- The angle integral. By the symmetry and because is even, . So has period . The sum at is the trapezoidal rule for one full period. For a periodic integrand that is times continuously differentiable its error is .
- The detector position. is not a bin center in general. The fractional index satisfies , and LININTERP returns the linear interpolant of the samples and . Linear interpolation is exact for linear functions, and its error is at most . Outside the detector it returns 0, which is the value of there only in the limit of a wide detector.
Summary. For a continuous with , whose projections are band-limited to and vanish outside the detector, lines L1 to L6 compute the exact samples of the filtered projections. Line L8 then evaluates Theorem 1 with the trapezoidal rule in and linear interpolation in . So the only errors on such data are the quadrature error in and the interpolation error in , and both go to 0 as grows and shrinks. A function with compact support is never exactly band-limited, so on real data the band limit is an approximation and the error has an aliasing part as well.
The Shepp-Logan kernel. Line L2 may use instead. These are the samples of the inverse transform of on , with . To see this, write the inverse transform at as and put :
because for each integer . So Lemmas 3 and 4 hold with this window in place of the plain ramp, and the result is blurred by the 2D filter with this window.
Complexity
In the real-RAM model with an FFT:
- Line L4 takes , because .
- Lines L5 and L6 take FFTs and inverse FFTs of length , so .
- Lines L7 and L8 take for each angle and pixel, so .
The total is time and extra space. Without an FFT, the direct sum of line L6 takes . In the usual case , the back projection dominates and the total is . Direct Fourier reconstruction takes , but it needs an interpolation in the Fourier plane, which gives worse artifacts.
Properties
- Linear. The output is a linear function of the sinogram. Noise in the data maps to noise in the image by a fixed linear map, and the ramp amplifies the high frequencies of the noise.
- One pass. There is no iteration and no stopping rule. Each projection can be filtered and back-projected as soon as it arrives.
- Not local in 2D. The ramp kernel decays like and does not vanish. So the value at a pixel depends on rays far from it, and truncated projections give errors everywhere (interior tomography).
- The back projection is an adjoint. Let be the pixel-driven projection matrix that puts the value of each pixel, times the pixel area over , on the two nearest bins with linear weights. Then lines L7 and L8 apply to the filtered sinogram.
Variants and improvements
- Windowed ramps. Multiply the ramp by a window (Shepp-Logan, cosine, Hamming, Hann) to reduce noise at the cost of resolution. See window functions.
- The Hilbert form. Since , the filter is a derivative followed by the Hilbert transform: .
- Fan beam and cone beam. Fan-beam FBP adds a weight and a distance factor. Another way is fan-to-parallel rebinning followed by parallel FBP. The Feldkamp-Davis-Kress method extends it to a circular cone beam, where it is exact only in the plane of the source circle.
- Local reconstruction. Lambda tomography replaces the ramp by a second derivative, which is local, and recovers the edges but not the values.
- Iterative methods. SART, SIRT, the Kaczmarz method and MLEM cost more, but they handle few views, missing angles and Poisson noise better.
When to use it
Use FBP when the projections are complete, dense and not too noisy: many angles over , an untruncated detector and enough dose. It is fast, it has no parameters except the window, and its output is linear and easy to analyze. For equal sample spacing on the outer ring of the Fourier plane, the arc between two angles at the radius , which is , must equal the radial step . This gives the rule . With far fewer angles, or with missing angles, use an iterative method (sparse-view CT, limited-angle tomography).
Pitfalls
- Circular wrap. Without zero padding to at least , the DFT product is a circular convolution. The negative tail of the kernel then wraps around and corrupts both ends of each filtered projection.
- Sampling on the DFT grid. A ramp sampled in the DFT domain is zero at the zero frequency, but the band-limited ramp restricted to spatial samples is not. The result is a constant offset and a dished image. Sample the kernel in space, as in line L2, and transform it (Kak and Slaney, Section 3.3.3).
- Wrong angle range or weight. The angles must cover evenly with the weight . Data over holds each line twice. Then the angle step is and the sum counts each line twice, so the weight is again , with the number of angles over .
- Detector offset. The center of rotation must project to the position in bin units. An offset of half a bin blurs the image, and larger offsets give arcs around points.
- No log transform. The method needs line integrals. Transmission data must first become by the Beer-Lambert law.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/filtered-back-projection/. The authors are listed in prov/M3HFA2.jsonl.
"""Filtered back-projection for parallel-beam data.
Conventions:
- The sinogram is a list of a projections, one per angle theta_k = k pi / a,
each a list of d detector values. Bin j has its center at
s_j = (j - (d - 1) / 2) tau, with the detector spacing tau.
- The projection at angle theta is the Radon transform
R f(theta, s) = integral f(s omega + t omega_perp) dt with
omega = (cos theta, sin theta).
- The output is an n x n image on [-1, 1]^2. Pixel (i, j) has its center at
x_j = -1 + (2 j + 1) / n and y_i = 1 - (2 i + 1) / n, so y goes up.
"""
import math
from imgkit import dft, idft, pixel_centers
def ram_lak_kernel(d, tau):
"""Samples h(m tau), m = -(d - 1) .. d - 1, of the ramp filter band-limited to 1 / (2 tau).
Entry m + d - 1 holds h(m tau): 1 / (4 tau^2) at m = 0, 0 at even m, and
-1 / (m^2 pi^2 tau^2) at odd m.
"""
out = []
for m in range(-(d - 1), d):
if m == 0:
out.append(1.0 / (4.0 * tau * tau))
elif m % 2 == 0:
out.append(0.0)
else:
out.append(-1.0 / (m * m * math.pi * math.pi * tau * tau))
return out
def shepp_logan_kernel(d, tau):
"""Samples h(m tau) = -2 / (pi^2 tau^2 (4 m^2 - 1)), m = -(d - 1) .. d - 1."""
return [-2.0 / (math.pi * math.pi * tau * tau * (4 * m * m - 1)) for m in range(-(d - 1), d)]
def filter_projection_direct(p, h, tau):
"""q_j = tau sum_k h((j - k) tau) p_k, the aperiodic convolution by a direct sum."""
d = len(p)
return [tau * sum(h[j - k + d - 1] * p[k] for k in range(d)) for j in range(d)]
def kernel_spectrum(h, d, length):
"""The DFT of length `length` of the kernel, wrapped so that h(0) sits at index 0."""
buf = [0.0] * length
for m in range(-(d - 1), d):
buf[m % length] = h[m + d - 1]
return dft(buf)
def filter_projection(p, hf, tau):
"""The same q as filter_projection_direct, by FFT with zero padding to len(hf) >= 2 d - 1."""
d, length = len(p), len(hf)
pf = dft(list(p) + [0.0] * (length - d))
q = idft([u * v for u, v in zip(pf, hf)])
return [tau * q[j].real for j in range(d)]
def lin_interp(q, u):
"""The linear interpolation of q at the fractional index u, and 0 outside [0, len(q) - 1]."""
b = math.floor(u)
w = u - b
val = 0.0
if 0 <= b < len(q):
val += (1.0 - w) * q[b]
if 0 <= b + 1 < len(q):
val += w * q[b + 1]
return val
def back_project(qs, tau, n):
"""(pi / a) sum_k q_k(x cos theta_k + y sin theta_k) at each pixel center, theta_k = k pi / a."""
a, d = len(qs), len(qs[0])
xs, ys = pixel_centers(n)
c0 = (d - 1) / 2.0
img = [[0.0] * n for _ in range(n)]
for k, q in enumerate(qs):
theta = k * math.pi / a
c, s = math.cos(theta), math.sin(theta)
for i, y in enumerate(ys): # @line L7
row = img[i]
for j, x in enumerate(xs):
row[j] += lin_interp(q, (x * c + y * s) / tau + c0) # @line L8
w = math.pi / a
return [[w * v for v in row] for row in img] # @line L9
def filtered_back_projection(sino, tau, n, kernel="ram-lak"):
"""Reconstruct an n x n image from a parallel-beam sinogram on [0, pi)."""
a, d = len(sino), len(sino[0]) # @line L1
if kernel == "ram-lak": # @line L2
h = ram_lak_kernel(d, tau)
elif kernel == "shepp-logan":
h = shepp_logan_kernel(d, tau)
else:
raise ValueError("unknown kernel")
length = 1 # @line L3
while length < 2 * d - 1:
length *= 2
hf = kernel_spectrum(h, d, length) # @line L4
qs = []
for k in range(a): # @line L5
qs.append(filter_projection(sino[k], hf, tau)) # @line L6
return back_project(qs, tau, n)
imgkit.py 322 lines
# SPDX-License-Identifier: MIT
# Shared helper of the imaging and inverse problems pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small images and signals for the imaging and inverse problems pages.
Conventions:
- A signal is a list of numbers. An image is a list of rows, img[i][j], with
row i from the top and column j from the left.
- An n x n image covers the square [-1, 1]^2. The center of pixel (i, j) is
x_j = -1 + (2 j + 1) / n and y_i = 1 - (2 i + 1) / n, so y goes up.
- DFT: X_k = sum_j x_j exp(-2 pi i j k / n), unnormalized; the inverse has
the factor 1 / n. Index k stands for frequency k for k < n / 2 and k - n
otherwise. fftshift moves the zero frequency to position n // 2.
- Periodic convolution kernels are stored with their center at index 0
(wrapped around), so a delta kernel gives the identity and no shift.
"""
import cmath
import math
# ------------------------------------------------------------------ images
def new_image(n1, n2, value=0.0):
"""An n1 x n2 image (n1 rows, n2 columns) filled with value."""
return [[value] * n2 for _ in range(n1)]
def img_add(a, b):
"""The pixelwise sum a + b."""
return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
def img_scale(a, c):
"""The image c a."""
return [[c * x for x in row] for row in a]
def img_dot(a, b):
"""<a, b> = sum conj(a_ij) b_ij."""
return sum(x.conjugate() * y for ra, rb in zip(a, b) for x, y in zip(ra, rb))
def img_norm(a):
"""The Euclidean (Frobenius) norm of an image."""
return math.sqrt(sum(abs(x) ** 2 for row in a for x in row))
def flatten(img):
"""Row-major vector of an image."""
return [x for row in img for x in row]
def unflatten(v, n1, n2):
"""The n1 x n2 image of a row-major vector."""
return [list(v[i * n2:(i + 1) * n2]) for i in range(n1)]
# ------------------------------------------------------------------ DFT
def _is_pow2(n):
return n > 0 and n & (n - 1) == 0
def _fft_pow2(x):
"""Iterative radix-2 FFT, unnormalized forward transform."""
n = len(x)
a = [complex(v) for v in x]
j = 0
for i in range(1, n):
bit = n >> 1
while j & bit:
j ^= bit
bit >>= 1
j |= bit
if i < j:
a[i], a[j] = a[j], a[i]
size = 2
while size <= n:
half = size // 2
tw = [cmath.exp(-2j * math.pi * k / size) for k in range(half)]
for start in range(0, n, size):
for k in range(half):
u = a[start + k]
v = a[start + k + half] * tw[k]
a[start + k] = u + v
a[start + k + half] = u - v
size *= 2
return a
def dft(x):
"""X_k = sum_j x_j exp(-2 pi i j k / n). Radix-2 FFT when n is a power of 2."""
n = len(x)
if n == 0:
return []
if _is_pow2(n):
return _fft_pow2(x)
w = [cmath.exp(-2j * math.pi * t / n) for t in range(n)]
return [sum(x[j] * w[(j * k) % n] for j in range(n)) for k in range(n)]
def idft(xf):
"""x_j = (1/n) sum_k X_k exp(2 pi i j k / n)."""
n = len(xf)
if n == 0:
return []
y = dft([complex(v).conjugate() for v in xf])
return [v.conjugate() / n for v in y]
def _rows_then_cols(img, f):
rows = [f(row) for row in img]
cols = [f(list(col)) for col in zip(*rows)]
return [list(r) for r in zip(*cols)]
def dft2(img):
"""2D DFT: X_kl = sum_jq x_jq exp(-2 pi i (j k / n1 + q l / n2))."""
return _rows_then_cols(img, dft)
def idft2(img):
"""Inverse 2D DFT, with the factor 1 / (n1 n2)."""
return _rows_then_cols(img, idft)
def _shift1(x, s):
return list(x[s:]) + list(x[:s])
def fftshift(x):
"""Move the zero frequency to position n // 2 (1D, or both axes of an image)."""
if x and isinstance(x[0], (list, tuple)):
rows = [fftshift(r) for r in x]
return _shift1(rows, (len(rows) + 1) // 2)
return _shift1(x, (len(x) + 1) // 2)
def ifftshift(x):
"""The inverse of fftshift (1D, or both axes of an image)."""
if x and isinstance(x[0], (list, tuple)):
rows = [ifftshift(r) for r in x]
return _shift1(rows, len(rows) // 2)
return _shift1(x, len(x) // 2)
def circ_conv(x, h):
"""Periodic convolution y_i = sum_j h_j x_{(i - j) mod n}, kernel centered at index 0."""
n = len(x)
nz = [(j, hj) for j, hj in enumerate(h) if hj != 0]
return [sum(hj * x[(i - j) % n] for j, hj in nz) for i in range(n)]
def circ_conv2(img, h):
"""Periodic 2D convolution with the kernel h centered at index (0, 0)."""
n1, n2 = len(img), len(img[0])
nz = [(p, q, h[p][q]) for p in range(len(h)) for q in range(len(h[0])) if h[p][q] != 0]
out = new_image(n1, n2)
for i in range(n1):
for j in range(n2):
out[i][j] = sum(v * img[(i - p) % n1][(j - q) % n2] for p, q, v in nz)
return out
# ------------------------------------------------------------------ phantoms
def pixel_centers(n):
"""(xs, ys): xs[j] = -1 + (2 j + 1) / n and ys[i] = 1 - (2 i + 1) / n."""
xs = [-1.0 + (2 * j + 1) / n for j in range(n)]
ys = [1.0 - (2 * i + 1) / n for i in range(n)]
return xs, ys
# Rows: rho, A, B, x0, y0, phi (degrees). A is the semi-axis along the
# direction phi (counterclockwise from the x axis), B the other semi-axis.
# Geometry and densities of Shepp and Logan (1974), as reproduced in Kak and
# Slaney, Principles of Computerized Tomographic Imaging, Table 3.1. The value
# at the center (0, 0) is 2 - 0.98 = 1.02.
SHEPP_LOGAN = [
(2.0, 0.92, 0.69, 0.0, 0.0, 90.0),
(-0.98, 0.874, 0.6624, 0.0, -0.0184, 90.0),
(-0.02, 0.31, 0.11, 0.22, 0.0, 72.0),
(-0.02, 0.41, 0.16, -0.22, 0.0, 108.0),
(0.01, 0.25, 0.21, 0.0, 0.35, 90.0),
(0.01, 0.046, 0.046, 0.0, 0.1, 0.0),
(0.01, 0.046, 0.046, 0.0, -0.1, 0.0),
(0.01, 0.046, 0.023, -0.08, -0.605, 0.0),
(0.01, 0.023, 0.023, 0.0, -0.605, 0.0),
(0.01, 0.046, 0.023, 0.06, -0.605, 90.0),
]
# The same ellipses with the gray levels of Toft (1996), which give more
# contrast. The value at the center is 1 - 0.8 = 0.2.
MODIFIED_SHEPP_LOGAN = [
(rho, a, b, x0, y0, phi)
for rho, (_, a, b, x0, y0, phi) in zip(
(1.0, -0.8, -0.2, -0.2, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1), SHEPP_LOGAN
)
]
def ellipse_value(x, y, table):
"""The phantom value at the point (x, y): the sum of rho over the ellipses that hold it."""
total = 0.0
for rho, a, b, x0, y0, phi in table:
c, s = math.cos(math.radians(phi)), math.sin(math.radians(phi))
dx, dy = x - x0, y - y0
u = dx * c + dy * s
v = -dx * s + dy * c
if (u / a) ** 2 + (v / b) ** 2 <= 1.0:
total += rho
return total
def ellipse_phantom(n, table):
"""The n x n image of an ellipse table, sampled at the pixel centers."""
xs, ys = pixel_centers(n)
return [[ellipse_value(x, y, table) for x in xs] for y in ys]
def disk_phantom(n, radius):
"""1 at pixel centers with x^2 + y^2 <= radius^2, 0 elsewhere."""
xs, ys = pixel_centers(n)
r2 = radius * radius
return [[1.0 if x * x + y * y <= r2 else 0.0 for x in xs] for y in ys]
def spikes_1d(n, positions, amplitudes):
"""A signal of length n with the given amplitudes at the given positions."""
out = [0.0] * n
for p, a in zip(positions, amplitudes):
out[p] += a
return out
# ------------------------------------------------------------------ projector
def parallel_beam_matrix(n, angles, nbins):
"""Pixel-driven discrete Radon transform of an n x n image on [-1, 1]^2.
Each pixel center (x, y) projects to s = x cos(theta) + y sin(theta). Its
value times the pixel area over the bin width is split linearly between
the two nearest bin centers. The bins cover [-sqrt(2), sqrt(2)]. Row
a * nbins + b holds angle a and bin b; column i * n + j holds pixel (i, j).
Returns the sparse rows, each a list of (column, weight) pairs.
Pixel-driven projection has a ripple: with a bin width close to the pixel
size, a disk projection is off by up to about 10 percent in some bins. A
bin of about twice the pixel size (nbins = 23 for n = 32) keeps it near
1 percent.
"""
xs, ys = pixel_centers(n)
smax = math.sqrt(2.0)
width = 2.0 * smax / nbins
scale = (2.0 / n) ** 2 / width
rows = []
for theta in angles:
c, s = math.cos(theta), math.sin(theta)
acc = [dict() for _ in range(nbins)]
for i, y in enumerate(ys):
for j, x in enumerate(xs):
t = (x * c + y * s + smax) / width - 0.5
b0 = math.floor(t)
frac = t - b0
col = i * n + j
for b, w in ((b0, 1.0 - frac), (b0 + 1, frac)):
if 0 <= b < nbins and w > 0.0:
acc[b][col] = acc[b].get(col, 0.0) + w * scale
rows.extend(sorted(d.items()) for d in acc)
return rows
def sp_matvec(rows, x):
"""y = A x for sparse rows of (column, weight) pairs."""
return [sum(w * x[c] for c, w in row) for row in rows]
def sp_rmatvec(rows, y, ncols):
"""x = A^H y for sparse rows of (column, weight) pairs and ncols columns."""
out = [0.0] * ncols
for row, yi in zip(rows, y):
if yi == 0:
continue
for c, w in row:
out[c] += w.conjugate() * yi
return out
# ------------------------------------------------------------------ noise
def gauss_noise(rng, shape, sigma):
"""Independent N(0, sigma^2) values: a list for an int shape, an image for (n1, n2)."""
if isinstance(shape, int):
return [rng.gauss(0.0, sigma) for _ in range(shape)]
n1, n2 = shape
return [[rng.gauss(0.0, sigma) for _ in range(n2)] for _ in range(n1)]
def _poisson_small(rng, lam):
"""Knuth's product method, exact for a mean lam <= 30."""
limit = math.exp(-lam)
k, p = 0, rng.random()
while p > limit:
k += 1
p *= rng.random()
return k
def poisson_sample(rng, lam):
"""An exact Poisson(lam) sample: a sum of Knuth samples with means at most 30."""
if lam < 0:
raise ValueError("negative mean")
total = 0
while lam > 30.0:
total += _poisson_small(rng, 30.0)
lam -= 30.0
if lam > 0.0:
total += _poisson_small(rng, lam)
return total
test_filtered_back_projection.py 141 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/filtered-back-projection/. The authors are listed in prov/M3HFA2.jsonl.
import math
import random
import imgkit as ik
from filtered_back_projection import (
back_project,
filter_projection,
filter_projection_direct,
filtered_back_projection,
kernel_spectrum,
ram_lak_kernel,
shepp_logan_kernel,
)
A, D, N = 32, 47, 32
TAU = 2.0 * math.sqrt(2.0) / D # the bins cover [-sqrt(2), sqrt(2)], as in imgkit
def ellipse_projection(table, theta, s):
"""The exact Radon transform of an ellipse table (Kak and Slaney, chapter 3)."""
total = 0.0
for rho, a, b, x0, y0, phi in table:
t = theta - math.radians(phi)
u = s - (x0 * math.cos(theta) + y0 * math.sin(theta))
a2 = a * a * math.cos(t) ** 2 + b * b * math.sin(t) ** 2
if u * u < a2:
total += 2.0 * rho * a * b / a2 * math.sqrt(a2 - u * u)
return total
def sinogram(fun, a=A, d=D, tau=TAU):
return [[fun(k * math.pi / a, (j - (d - 1) / 2.0) * tau) for j in range(d)] for k in range(a)]
def test_kernel_values() -> None:
h = ram_lak_kernel(4, 0.5)
assert len(h) == 7
assert h[3] == 1.0
assert h[1] == 0.0 and h[5] == 0.0
assert abs(h[2] + 4.0 / math.pi ** 2) < 1e-15
assert abs(h[0] + 4.0 / (9.0 * math.pi ** 2)) < 1e-15
g = shepp_logan_kernel(4, 0.5)
assert abs(g[3] - 8.0 / math.pi ** 2) < 1e-15
assert abs(g[2] + 8.0 / (3.0 * math.pi ** 2)) < 1e-15
def test_kernel_frequency_response() -> None:
# tau sum_m h(m tau) cos(2 pi m nu tau) -> |nu| (Ram-Lak) and sin(pi nu tau) / (pi tau) (Shepp-Logan)
tau, d = 1.0, 4001
h, g = ram_lak_kernel(d, tau), shepp_logan_kernel(d, tau)
for nu in (0.05, 0.2, 0.35, 0.45):
r = sum(tau * h[m + d - 1] * math.cos(2 * math.pi * m * nu * tau) for m in range(-(d - 1), d))
s = sum(tau * g[m + d - 1] * math.cos(2 * math.pi * m * nu * tau) for m in range(-(d - 1), d))
assert abs(r - nu) < 1e-3
assert abs(s - math.sin(math.pi * nu * tau) / (math.pi * tau)) < 1e-3
def test_fft_filter_equals_direct_sum() -> None:
rng = random.Random(11)
for d in (1, 2, 7, 16, 47):
p = [rng.uniform(-1.0, 1.0) for _ in range(d)]
h = ram_lak_kernel(d, 0.1)
length = 1
while length < 2 * d - 1:
length *= 2
q1 = filter_projection(p, kernel_spectrum(h, d, length), 0.1)
q2 = filter_projection_direct(p, h, 0.1)
assert max(abs(u - v) for u, v in zip(q1, q2)) < 1e-10
def test_back_projection_is_scaled_adjoint_of_projector() -> None:
# back_project with linear interpolation is (pi / a) / scale times the transpose of the
# pixel-driven projector of imgkit, and that pair passes the adjoint test.
a, d, n = 8, 23, 12
tau = 2.0 * math.sqrt(2.0) / d
angles = [k * math.pi / a for k in range(a)]
rows = ik.parallel_beam_matrix(n, angles, d)
scale = (2.0 / n) ** 2 / tau
rng = random.Random(5)
y = [rng.gauss(0.0, 1.0) for _ in range(a * d)]
x = [rng.gauss(0.0, 1.0) for _ in range(n * n)]
bp = ik.flatten(back_project([y[k * d:(k + 1) * d] for k in range(a)], tau, n))
at_y = ik.sp_rmatvec(rows, y, n * n)
c = (math.pi / a) / scale
assert max(abs(u - c * v) for u, v in zip(bp, at_y)) < 1e-12
ax = ik.sp_matvec(rows, x)
lhs = sum(u * v for u, v in zip(ax, y))
rhs = sum(u * v for u, v in zip(x, bp)) / c
norm = math.sqrt(sum(v * v for v in ax)) * math.sqrt(sum(v * v for v in y))
assert abs(lhs - rhs) <= 1e-10 * norm
def test_gaussian_known_answer() -> None:
# f(x) = exp(-pi |x|^2 / w^2) has R f(theta, s) = w exp(-pi s^2 / w^2).
w = 0.5
sino = sinogram(lambda th, s: w * math.exp(-math.pi * s * s / (w * w)))
img = filtered_back_projection(sino, TAU, N)
xs, ys = ik.pixel_centers(N)
err = max(abs(img[i][j] - math.exp(-math.pi * (xs[j] ** 2 + ys[i] ** 2) / (w * w))) for i in range(N) for j in range(N))
assert err < 0.03 # measured 0.017 for a = 32, d = 47, n = 32
def test_disk_interior() -> None:
sino = sinogram(lambda th, s: 2.0 * math.sqrt(0.25 - s * s) if s * s < 0.25 else 0.0)
xs, ys = ik.pixel_centers(N)
for kernel in ("ram-lak", "shepp-logan"):
img = filtered_back_projection(sino, TAU, N, kernel)
inner = [img[i][j] for i in range(N) for j in range(N) if xs[j] ** 2 + ys[i] ** 2 < 0.35 ** 2]
outer = [img[i][j] for i in range(N) for j in range(N) if xs[j] ** 2 + ys[i] ** 2 > 0.65 ** 2]
assert max(abs(v - 1.0) for v in inner) < 0.02 # measured 0.010
assert max(abs(v) for v in outer) < 0.05
def test_shepp_logan_center() -> None:
sino = sinogram(lambda th, s: ellipse_projection(ik.SHEPP_LOGAN, th, s))
img = filtered_back_projection(sino, TAU, N)
center = (img[15][15] + img[15][16] + img[16][15] + img[16][16]) / 4.0
assert abs(center - 1.02) < 0.02 # measured 1.017
def test_linear_and_zero() -> None:
rng = random.Random(3)
s1 = [[rng.uniform(0, 1) for _ in range(9)] for _ in range(4)]
s2 = [[rng.uniform(0, 1) for _ in range(9)] for _ in range(4)]
s3 = [[u + 2.0 * v for u, v in zip(r1, r2)] for r1, r2 in zip(s1, s2)]
f1, f2, f3 = (filtered_back_projection(s, 0.3, 6) for s in (s1, s2, s3))
assert max(abs(f3[i][j] - f1[i][j] - 2.0 * f2[i][j]) for i in range(6) for j in range(6)) < 1e-12
z = filtered_back_projection([[0.0] * 9 for _ in range(4)], 0.3, 6)
assert all(v == 0.0 for row in z for v in row)
def test_hand_trace_center() -> None:
# Disk of radius 1/2, d = 7, tau = 1/4: the filtered center bin is 0.29803,
# and with 4 angles the value at the origin is pi times that.
p = [2.0 * math.sqrt(max(0.0, 0.25 - ((j - 3) * 0.25) ** 2)) for j in range(7)]
q = filter_projection_direct(p, ram_lak_kernel(7, 0.25), 0.25)
assert abs(q[3] - 0.29803) < 1e-5
assert abs(math.pi * q[3] - 0.93628) < 1e-5
History
The formula that FBP discretizes is the Radon inversion formula in its Fourier form. Ramachandran and Lakshminarayanan published in 1971 the method of convolution with the sampled band-limited ramp, in place of the Fourier transforms of the earlier methods. Shepp and Logan proposed their smoother kernel in 1974, in the same paper that introduced their head phantom. Kak and Slaney give the discrete form with the zero padding rule that the code follows.
References
- G. N. Ramachandran and A. V. Lakshminarayanan, Three-dimensional reconstruction from radiographs and electron micrographs, application of convolutions instead of Fourier transforms, Proceedings of the National Academy of Sciences 68(9), 1971, pp. 2236 to 2240
- L. A. Shepp and B. F. Logan, The Fourier reconstruction of a head section, IEEE Transactions on Nuclear Science 21(3), 1974, pp. 21 to 43 (the smoother kernel and the head phantom)
- A. C. Kak and M. Slaney, Principles of Computerized Tomographic Imaging, SIAM Classics in Applied Mathematics 33, 2001, Chapter 3, Section 3.3 (the filtered back-projection formula, equation 45, and the computer implementation of Section 3.3.3)
- F. Natterer, The Mathematics of Computerized Tomography, SIAM Classics in Applied Mathematics 32, 2001, Section V.1, filtered backprojection
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag M3HFA2 Edit this page History Report an error Markdown