Algorithm Search⌘K

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
Properties
deterministicnot in placenot iterativelineariterative
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 aa angles, dd detector bins and an n×nn \times n image it takes O(adlog⁡d+an2)O(a d \log d + a n^2) 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 P[k][j]P[k][j] for k=0,…,a−1k = 0, \ldots, a - 1 and j=0,…,d−1j = 0, \ldots, d - 1. Row kk samples the projection Rf(θk,⋅)\mathcal{R}f(\theta_k, \cdot) of an unknown image ff at the angle θk=kπ/a\theta_k = k\pi/a. Bin jj has its center at sj=(j−(d−1)/2)τs_j = (j - (d-1)/2)\tau, with the detector spacing τ\tau. Here Rf(θ,s)=∫f(s ω+t ω⊥) dt\mathcal{R}f(\theta, s) = \int f(s\,\omega + t\,\omega^\perp)\,dt is the Radon transform, with ω=(cos⁡θ,sin⁡θ)\omega = (\cos\theta, \sin\theta) and ω⊥=(−sin⁡θ,cos⁡θ)\omega^\perp = (-\sin\theta, \cos\theta). The output is an n×nn \times n image on the square [−1,1]2[-1, 1]^2. Pixel (i,j)(i, j) has its center at xj=−1+(2j+1)/nx_j = -1 + (2j+1)/n and yi=1−(2i+1)/ny_i = 1 - (2i+1)/n, so row 0 is at the top and yy goes up.

FBP evaluates the inversion formula

f(x)=∫0π(h∗Rf(θ,⋅))(x⋅ω(θ)) dθ,f(x) = \int_0^\pi (h * \mathcal{R}f(\theta, \cdot))(x \cdot \omega(\theta))\,d\theta,

where hh is the filter with the frequency response ∣σ∣|\sigma|. 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

  1. FBP(P, τ, n) ▷ P[k][j]: angle θ_k = kπ/a, bin center s_j = (j - (d-1)/2) τ
  2. 1a, d ← the number of rows and of columns of P
  3. 2h[m] ← h(mτ) for m = -(d-1) .. d-1 ▷ Ram-Lak or Shepp-Logan kernel
  4. 3L ← the smallest power of 2 with L ≥ 2d - 1
  5. 4Ĥ ← DFT_L(h), with h[m] stored at index m mod L
  6. 5for k ← 0 to a - 1 do
  7. 6q_k ← τ · (the first d entries of IDFT_L(DFT_L(P[k] padded with zeros to L) · Ĥ))
  8. 7for each pixel (i, j) with center (x_j, y_i) do
  9. 8f[i][j] ← (π/a) Σ_k LININTERP(q_k, (x_j cos θ_k + y_i sin θ_k)/τ + (d-1)/2)
  10. 9return f

Line L2 samples the ramp filter cut off at the Nyquist frequency 1/(2τ)1/(2\tau) of the detector. The Ram-Lak kernel of Ramachandran and Lakshminarayanan is

h(0)=14τ2,h(mτ)=0 for even m≠0,h(mτ)=−1m2π2τ2 for odd m.h(0) = \frac{1}{4\tau^2}, \qquad h(m\tau) = 0 \text{ for even } m \ne 0, \qquad h(m\tau) = -\frac{1}{m^2\pi^2\tau^2} \text{ for odd } m.

The kernel of Shepp and Logan is h(mτ)=−2/(π2τ2(4m2−1))h(m\tau) = -2/(\pi^2\tau^2(4m^2 - 1)). Its frequency response is ∣ν∣ sinc(ντ)|\nu|\,\mathrm{sinc}(\nu\tau), so it damps the highest frequencies and the noise there. Lines L3 to L6 compute the aperiodic discrete convolution qk[j]=τ∑l=0d−1h((j−l)τ) P[k][l]q_k[j] = \tau \sum_{l=0}^{d-1} h((j - l)\tau)\,P[k][l] with the fast Fourier transform. The zero padding to L≥2d−1L \ge 2d - 1 makes the circular convolution of the DFT equal to the aperiodic one on the dd outputs. Line L8 is the discrete back projection: the sum over the angles approximates the integral over [0,π)[0, \pi), and LININTERP reads the filtered projection between two bin centers by linear interpolation, with 0 outside the detector. The factor π/a\pi/a is the angle step.

Example

Take the disk of radius 1/21/2 with density 1. Its projection is 21/4−s22\sqrt{1/4 - s^2} at each angle. With d=7d = 7 bins and τ=1/4\tau = 1/4 the bin centers are s=−0.75,−0.5,…,0.75s = -0.75, -0.5, \ldots, 0.75, and

quantity values at j=0,…,6j = 0, \ldots, 6
projection P[k][j]P[k][j] 0, 0, 0.8660, 1, 0.8660, 0, 0
kernel h(mτ)h(m\tau), m=−3,…,3m = -3, \ldots, 3 -0.1801, 0, -1.6211, 4, -1.6211, 0, -0.1801
filtered qk[j]q_k[j] -0.0450, -0.3900, 0.4607, 0.2980, 0.4607, -0.3900, -0.0450

The center value is qk[3]=τ(4⋅1−2⋅1.6211⋅0.8660)=0.2980q_k[3] = \tau(4 \cdot 1 - 2 \cdot 1.6211 \cdot 0.8660) = 0.2980. The filter makes the values negative just outside the disk, at j=1j = 1 and j=5j = 5. The disk is the same at each angle, so with a=4a = 4 angles the value at the origin is (π/4)⋅4⋅0.2980=0.9363(\pi/4) \cdot 4 \cdot 0.2980 = 0.9363. The true value is 1. The error comes from the coarse detector: 7 bins of width 1/41/4 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 a=32a = 32 angles, d=47d = 47 bins, τ=22/47\tau = 2\sqrt{2}/47 and n=32n = 32. These numbers are measurements of this setup, not bounds.

phantom Ram-Lak kernel Shepp-Logan kernel
Gaussian e−4π∣x∣2e^{-4\pi\vert x\vert^2}, largest error 0.0170 0.0239
disk of radius 1/21/2, largest error for ∣x∣<0.35\vert x\vert < 0.35 0.0098 0.0093
disk of radius 1/21/2, largest error at the edge 0.40 0.40
Shepp-Logan phantom, value at pixel (16,16)(16, 16), 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 f=R#(h∗Rf)f = \mathcal{R}^\#(h * \mathcal{R}f) for continuous ff with an integrable Fourier transform. The Jacobian ∣σ∣|\sigma| of polar coordinates is the ramp. Second, the Ram-Lak values of line L2 are the samples of the inverse transform of ∣ν∣|\nu| on ∣ν∣≤1/(2τ)|\nu| \le 1/(2\tau). Third, if each projection is band-limited to ∣ν∣<1/(2τ)|\nu| < 1/(2\tau), the discrete sum of line L6 gives the exact samples of the filtered projection, by the sampling theorem. Fourth, with L≥2d−1L \ge 2d - 1 the FFT product of lines L3 to L6 equals that sum, by the convolution theorem. Line L8 is then the trapezoidal rule in θ\theta for a function of period π\pi, plus linear interpolation in ss. These two steps are the only approximations on band-limited data.

Proof: Correctness of filtered back-projectionfull

We use the conventions of the page. ω(θ)=(cos⁡θ,sin⁡θ)\omega(\theta) = (\cos\theta, \sin\theta) and ω⊥(θ)=(−sin⁡θ,cos⁡θ)\omega^\perp(\theta) = (-\sin\theta, \cos\theta). The Radon transform is Rf(θ,s)=∫Rf(s ω+t ω⊥) dt\mathcal{R}f(\theta, s) = \int_{\mathbb{R}} f(s\,\omega + t\,\omega^\perp)\,dt for θ∈[0,π)\theta \in [0, \pi) and s∈Rs \in \mathbb{R}. The Fourier transform uses ordinary frequency, Ff(ξ)=∫f(x)e−2πix⋅ξ dx\mathcal{F}f(\xi) = \int f(x) e^{-2\pi i x \cdot \xi}\,dx. For a fixed angle we write pθ(s)=Rf(θ,s)p_\theta(s) = \mathcal{R}f(\theta, s) and Pθ(σ)=∫pθ(s)e−2πisσ dsP_\theta(\sigma) = \int p_\theta(s) e^{-2\pi i s \sigma}\,ds.

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 f∈L1(R2)f \in L^1(\mathbb{R}^2). Then for each θ\theta, pθ∈L1(R)p_\theta \in L^1(\mathbb{R}) and Pθ(σ)=Ff(σ ω(θ))P_\theta(\sigma) = \mathcal{F}f(\sigma\,\omega(\theta)) for all σ∈R\sigma \in \mathbb{R}.

Proof. The map (s,t)↦s ω+t ω⊥(s, t) \mapsto s\,\omega + t\,\omega^\perp is a rotation, so its Jacobian is 1, and s=x⋅ωs = x \cdot \omega at the point x=s ω+t ω⊥x = s\,\omega + t\,\omega^\perp. By Fubini, ∫∣pθ(s)∣ ds≤∫∫∣f(s ω+t ω⊥)∣ dt ds=∥f∥1\int |p_\theta(s)|\,ds \le \int\int |f(s\,\omega + t\,\omega^\perp)|\,dt\,ds = \|f\|_1, and

Pθ(σ)=∫∫f(s ω+t ω⊥) e−2πisσ dt ds=∫R2f(x) e−2πi(x⋅ω)σ dx=Ff(σ ω).□P_\theta(\sigma) = \int\int f(s\,\omega + t\,\omega^\perp)\, e^{-2\pi i s\sigma}\,dt\,ds = \int_{\mathbb{R}^2} f(x)\, e^{-2\pi i (x\cdot\omega)\sigma}\,dx = \mathcal{F}f(\sigma\,\omega). \qquad \square

Theorem 1 (filtered back-projection formula). Let f∈L1(R2)f \in L^1(\mathbb{R}^2) be continuous, with Ff∈L1(R2)\mathcal{F}f \in L^1(\mathbb{R}^2). Put qθ(s)=∫R∣σ∣ Pθ(σ) e2πisσ dσq_\theta(s) = \int_{\mathbb{R}} |\sigma|\, P_\theta(\sigma)\, e^{2\pi i s\sigma}\,d\sigma. Then for every x∈R2x \in \mathbb{R}^2

f(x)=∫0πqθ(x⋅ω(θ)) dθ.f(x) = \int_0^\pi q_\theta(x \cdot \omega(\theta))\,d\theta.

Proof. Because Ff∈L1\mathcal{F}f \in L^1 and ff is continuous, the Fourier inversion formula holds at every point: f(x)=∫R2Ff(ξ)e2πix⋅ξ dξf(x) = \int_{\mathbb{R}^2} \mathcal{F}f(\xi) e^{2\pi i x\cdot\xi}\,d\xi. Write ξ=σ ω(θ)\xi = \sigma\,\omega(\theta) with θ∈[0,π)\theta \in [0, \pi) and σ∈R\sigma \in \mathbb{R}. This map covers R2\mathbb{R}^2 once, except for the null set ξ=0\xi = 0, and dξ=∣σ∣ dσ dθd\xi = |\sigma|\,d\sigma\,d\theta. So

f(x)=∫0π∫RFf(σ ω) ∣σ∣ e2πiσ(x⋅ω) dσ dθ.f(x) = \int_0^\pi \int_{\mathbb{R}} \mathcal{F}f(\sigma\,\omega)\, |\sigma|\, e^{2\pi i \sigma (x\cdot\omega)}\,d\sigma\,d\theta.

The double integral converges absolutely, because its absolute value integrates to ∥Ff∥1\|\mathcal{F}f\|_1. So by Fubini the inner integral exists for almost every θ\theta. By Lemma 1, Ff(σ ω)=Pθ(σ)\mathcal{F}f(\sigma\,\omega) = P_\theta(\sigma), and the inner integral is qθ(x⋅ω)q_\theta(x\cdot\omega). □\square

The filter ∣σ∣|\sigma| is the ramp. Its inverse transform hh is not a function, so qθ=h∗pθq_\theta = h * p_\theta holds only in the sense of distributions. The algorithm replaces ∣σ∣|\sigma| with a band-limited ramp.

Lemma 2 (Ram-Lak kernel). Let τ>0\tau > 0, B=1/(2τ)B = 1/(2\tau), and hB(s)=∫−BB∣ν∣ e2πisν dνh_B(s) = \int_{-B}^{B} |\nu|\, e^{2\pi i s\nu}\,d\nu. Then hB(0)=1/(4τ2)h_B(0) = 1/(4\tau^2), hB(mτ)=0h_B(m\tau) = 0 for even m≠0m \ne 0, and hB(mτ)=−1/(m2π2τ2)h_B(m\tau) = -1/(m^2\pi^2\tau^2) for odd mm.

Proof. ∣ν∣|\nu| is even, so hB(s)=2∫0Bνcos⁡(2πsν) dνh_B(s) = 2\int_0^B \nu \cos(2\pi s\nu)\,d\nu. At s=0s = 0 this is B2=1/(4τ2)B^2 = 1/(4\tau^2). For s=mτs = m\tau with m≠0m \ne 0, put c=2πmτc = 2\pi m\tau. Integration by parts gives

∫0Bνcos⁡(cν) dν=Bsin⁡(cB)c+cos⁡(cB)−1c2.\int_0^B \nu\cos(c\nu)\,d\nu = \frac{B \sin(cB)}{c} + \frac{\cos(cB) - 1}{c^2}.

Here cB=πmcB = \pi m, so sin⁡(cB)=0\sin(cB) = 0 and cos⁡(cB)=(−1)m\cos(cB) = (-1)^m. Hence hB(mτ)=2((−1)m−1)/(4π2m2τ2)h_B(m\tau) = 2((-1)^m - 1)/(4\pi^2 m^2\tau^2). This is 0 for even mm and −1/(π2m2τ2)-1/(\pi^2 m^2\tau^2) for odd mm. □\square

Line L2 with the Ram-Lak choice stores exactly these values for ∣m∣≤d−1|m| \le d - 1.

Lemma 3 (exact discrete filtering). Let p∈L1(R)p \in L^1(\mathbb{R}) be continuous, with P(ν)=0P(\nu) = 0 for ∣ν∣≥B=1/(2τ)|\nu| \ge B = 1/(2\tau), and with ∑k∣p(kτ)∣<∞\sum_k |p(k\tau)| < \infty. Then for every integer jj

(hB∗p)(jτ):=∫−BB∣ν∣ P(ν) e2πijτν dν=τ∑k∈ZhB((j−k)τ) p(kτ).(h_B * p)(j\tau) := \int_{-B}^{B} |\nu|\, P(\nu)\, e^{2\pi i j\tau\nu}\,d\nu = \tau \sum_{k \in \mathbb{Z}} h_B((j - k)\tau)\, p(k\tau).

Proof. The function ν↦P(ν)\nu \mapsto P(\nu) on [−B,B][-B, B] extends to a function of period 2B=1/τ2B = 1/\tau. Its Fourier coefficients are τ∫−BBP(ν)e2πikτν dν=τ p(kτ)\tau\int_{-B}^{B} P(\nu) e^{2\pi i k\tau\nu}\,d\nu = \tau\,p(k\tau), by the inversion formula for the band-limited pp. The coefficients are absolutely summable, so the Fourier series converges uniformly to the continuous periodic extension: P(ν)=τ∑kp(kτ) e−2πikτνP(\nu) = \tau\sum_k p(k\tau)\,e^{-2\pi i k\tau\nu} for ∣ν∣≤B|\nu| \le B. Put this into the left side. The sum converges uniformly and ∣ν∣|\nu| is bounded on [−B,B][-B, B], so the sum and the integral commute:

∫−BB∣ν∣ P(ν) e2πijτν dν=τ∑kp(kτ)∫−BB∣ν∣ e2πi(j−k)τν dν=τ∑kp(kτ) hB((j−k)τ).□\int_{-B}^{B} |\nu|\, P(\nu)\, e^{2\pi i j\tau\nu}\,d\nu = \tau\sum_k p(k\tau) \int_{-B}^{B} |\nu|\, e^{2\pi i (j-k)\tau\nu}\,d\nu = \tau\sum_k p(k\tau)\, h_B((j-k)\tau). \qquad \square

If also p(kτ)=0p(k\tau) = 0 for k<0k < 0 and k≥dk \ge d, the sum has only the terms 0≤k≤d−10 \le k \le d - 1. Then j−kj - k lies in {−(d−1),…,d−1}\{-(d-1), \ldots, d-1\} for 0≤j≤d−10 \le j \le d - 1, which is the range that line L2 stores. The sinogram index jj is the detector position sj=(j−(d−1)/2)τs_j = (j - (d-1)/2)\tau. A shift of the origin by (d−1)τ/2(d-1)\tau/2 changes neither side, because both sides are convolutions.

Lemma 4 (zero padding). Let L≥2d−1L \ge 2d - 1. Let uk=pku_k = p_k for 0≤k≤d−10 \le k \le d - 1 and uk=0u_k = 0 for d≤k≤L−1d \le k \le L - 1. Let wm mod L=hmw_{m \bmod L} = h_m for ∣m∣≤d−1|m| \le d - 1 and wr=0w_r = 0 at the other indices rr. Let y=IDFTL(DFTL(u)⋅DFTL(w))y = \mathrm{IDFT}_L(\mathrm{DFT}_L(u) \cdot \mathrm{DFT}_L(w)). Then yj=∑k=0d−1hj−k pky_j = \sum_{k=0}^{d-1} h_{j-k}\, p_k for 0≤j≤d−10 \le j \le d - 1.

Proof. First, ww is well defined. Two values m≠m′m \ne m' in {−(d−1),…,d−1}\{-(d-1), \ldots, d-1\} differ by at most 2d−2<L2d - 2 < L, so m mod L≠m′ mod Lm \bmod L \ne m' \bmod L. By the convolution theorem for the DFT, yj=∑k=0L−1uk w(j−k) mod L=∑k=0d−1pk w(j−k) mod Ly_j = \sum_{k=0}^{L-1} u_k\, w_{(j-k) \bmod L} = \sum_{k=0}^{d-1} p_k\, w_{(j-k) \bmod L}. For 0≤j,k≤d−10 \le j, k \le d - 1 we have ∣j−k∣≤d−1|j - k| \le d - 1, so w(j−k) mod L=hj−kw_{(j-k) \bmod L} = h_{j-k}. □\square

Lines L3 and L4 build LL and DFTL(w)\mathrm{DFT}_L(w). Line L6 builds uu, applies the product and multiplies by τ\tau. The data and the kernel are real, so yy is real, and taking the real part removes only rounding errors. With Lemmas 2, 3 and 4, line L6 gives qk[j]=(hB∗pθk)(sj)q_k[j] = (h_B * p_{\theta_k})(s_j) exactly, for each projection that is band-limited to ∣ν∣<1/(2τ)|\nu| < 1/(2\tau) and zero outside the detector. If L<2d−1L < 2d - 1, 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 qθq_\theta replaced by hB∗pθh_B * p_\theta.

  1. The angle integral. By the symmetry Rf(θ+π,−s)=Rf(θ,s)\mathcal{R}f(\theta + \pi, -s) = \mathcal{R}f(\theta, s) and because hBh_B is even, qθ+π(−s)=qθ(s)q_{\theta+\pi}(-s) = q_\theta(s). So θ↦qθ(x⋅ω(θ))\theta \mapsto q_\theta(x\cdot\omega(\theta)) has period π\pi. The sum (π/a)∑k=0a−1(\pi/a)\sum_{k=0}^{a-1} at θk=kπ/a\theta_k = k\pi/a is the trapezoidal rule for one full period. For a periodic integrand that is rr times continuously differentiable its error is O(a−r)O(a^{-r}).
  2. The detector position. x⋅ω(θk)x\cdot\omega(\theta_k) is not a bin center in general. The fractional index u=x⋅ω/τ+(d−1)/2u = x\cdot\omega/\tau + (d-1)/2 satisfies su=x⋅ωs_u = x\cdot\omega, and LININTERP returns the linear interpolant of the samples qk[⌊u⌋]q_k[\lfloor u\rfloor] and qk[⌊u⌋+1]q_k[\lfloor u\rfloor + 1]. Linear interpolation is exact for linear functions, and its error is at most τ2max⁡∣qθ′′∣/8\tau^2 \max|q_\theta''| / 8. Outside the detector it returns 0, which is the value of qθq_\theta there only in the limit of a wide detector.

Summary. For a continuous ff with Ff∈L1\mathcal{F}f \in L^1, whose projections are band-limited to ∣ν∣<1/(2τ)|\nu| < 1/(2\tau) 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 θ\theta and linear interpolation in ss. So the only errors on such data are the quadrature error in θ\theta and the interpolation error in ss, and both go to 0 as aa grows and τ\tau 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 h(mτ)=−2/(π2τ2(4m2−1))h(m\tau) = -2/(\pi^2\tau^2(4m^2 - 1)) instead. These are the samples of the inverse transform of ∣ν∣ sinc(ντ)|\nu|\,\mathrm{sinc}(\nu\tau) on [−B,B][-B, B], with sinc(z)=sin⁡(πz)/(πz)\mathrm{sinc}(z) = \sin(\pi z)/(\pi z). To see this, write the inverse transform at s=mτs = m\tau as 2∫0Bν sinc(ντ)cos⁡(2πmτν) dν2\int_0^B \nu\,\mathrm{sinc}(\nu\tau)\cos(2\pi m\tau\nu)\,d\nu and put u=πτνu = \pi\tau\nu:

2π2τ2∫0π/2sin⁡ucos⁡(2mu) du=1π2τ2(11+2m+11−2m)=−2π2τ2(4m2−1),\frac{2}{\pi^2\tau^2}\int_0^{\pi/2} \sin u \cos(2mu)\,du = \frac{1}{\pi^2\tau^2}\left(\frac{1}{1+2m} + \frac{1}{1-2m}\right) = \frac{-2}{\pi^2\tau^2(4m^2 - 1)},

because cos⁡((1±2m)π/2)=0\cos((1 \pm 2m)\pi/2) = 0 for each integer mm. So Lemmas 3 and 4 hold with this window in place of the plain ramp, and the result is ff blurred by the 2D filter with this window.

Complexity

In the real-RAM model with an FFT:

  • Line L4 takes O(dlog⁡d)O(d \log d), because L<4dL < 4d.
  • Lines L5 and L6 take aa FFTs and aa inverse FFTs of length LL, so O(adlog⁡d)O(a d \log d).
  • Lines L7 and L8 take O(1)O(1) for each angle and pixel, so O(an2)O(a n^2).

The total is O(adlog⁡d+an2)O(a d \log d + a n^2) time and O(ad+n2)O(a d + n^2) extra space. Without an FFT, the direct sum of line L6 takes O(ad2)O(a d^2). In the usual case a≈d≈na \approx d \approx n, the back projection dominates and the total is O(n3)O(n^3). Direct Fourier reconstruction takes O(adlog⁡d+n2log⁡n)O(a d \log d + n^2 \log n), 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 1/s21/s^2 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 AA be the pixel-driven projection matrix that puts the value of each pixel, times the pixel area (2/n)2(2/n)^2 over τ\tau, on the two nearest bins with linear weights. Then lines L7 and L8 apply (π/a) (τ/(2/n)2) AT(\pi/a)\,(\tau/(2/n)^2)\,A^T 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 ∣σ∣=(2π)−1 (2πiσ)(−i sgn σ)|\sigma| = (2\pi)^{-1}\,(2\pi i\sigma)(-i\,\mathrm{sgn}\,\sigma), the filter is a derivative followed by the Hilbert transform: f=(2π)−1R# H ∂sRff = (2\pi)^{-1}\mathcal{R}^\#\,H\,\partial_s \mathcal{R}f.
  • 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 [0,π)[0, \pi), 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 1/(2τ)1/(2\tau), which is π/(2aτ)\pi/(2a\tau), must equal the radial step 1/(dτ)1/(d\tau). This gives the rule a≈πd/2a \approx \pi d/2. 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 2d−12d - 1, 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 ∣k∣|k| on the DFT grid. A ramp sampled in the DFT domain is zero at the zero frequency, but the band-limited ramp restricted to dd 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 [0,π)[0, \pi) evenly with the weight π/a\pi/a. Data over [0,2π)[0, 2\pi) holds each line twice. Then the angle step is 2π/a2\pi/a and the sum counts each line twice, so the weight is again π/a\pi/a, with aa the number of angles over [0,2π)[0, 2\pi).
  • Detector offset. The center of rotation must project to the position (d−1)/2(d-1)/2 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 −ln⁡(I/I0)-\ln(I/I_0) 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.

filtered_back_projection.pyI0RawGitHub
# 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

  1. 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
  2. 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)
  3. 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)
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example