Algorithm Search⌘K

Algorithmcore

Fan-to-parallel rebinning

Also called fan-beam rebinning.

Turn fan-beam CT data into a parallel-beam sinogram. Each parallel ray is a fan ray with a known source angle and fan angle, read from the fan data by interpolation.

Time
O(a d) worst
Space
O(a d) extra
Where
a = the number of parallel angles; d = the number of parallel detector bins; n = the side of the n x n output image
Properties
deterministicnot in placenot iterativelineariterative

Fan-to-parallel rebinning converts the data of a fan-beam CT scanner into a parallel-beam sinogram. Each ray of a parallel projection is also a ray of some fan: its source angle and its fan angle follow from the angle and the offset of the line by one arcsine. The algorithm reads that fan ray from the measured data by bilinear interpolation and stores it. After rebinning, ordinary parallel-beam filtered back-projection, or any other parallel method, reconstructs the image. Rebinning an a×da \times d parallel sinogram takes O(ad)O(a d) time. Kak and Slaney call it re-sorting.

In plain words

A fan-beam scanner measures many rays at each source position, and the rays spread out from the source. A parallel scanner measures, at each angle, rays that are all parallel. The two scanners measure the same kind of thing: the total absorption along straight lines. Only the way the lines are grouped differs.

Rebinning regroups the lines. For each line that a parallel projection needs, it finds the source position from which that line was shot and the detector cell that caught it. The scanner rarely has a source exactly at that position, or a cell exactly at that spot, so the value is mixed from the four nearest measurements. When every parallel line has a value, the data looks as if a parallel scanner had made it, and the parallel method takes over.

The problem

The source at the angle β\beta is at S(β)=D ω⊥(β)S(\beta) = D\,\omega^\perp(\beta), at the distance DD from the center, with ω(β)=(cos⁡β,sin⁡β)\omega(\beta) = (\cos\beta, \sin\beta) and ω⊥(β)=(−sin⁡β,cos⁡β)\omega^\perp(\beta) = (-\sin\beta, \cos\beta). The ray with the fan angle γ\gamma is the line with the angle θ=β+γ\theta = \beta + \gamma and the offset s=Dsin⁡γs = D\sin\gamma, so the fan data is

g(β,γ)=Rf(β+γ,Dsin⁡γ),g(\beta, \gamma) = \mathcal{R}f(\beta + \gamma, D\sin\gamma),

with the Radon transform Rf(θ,s)=∫f(s ω+t ω⊥) dt\mathcal{R}f(\theta, s) = \int f(s\,\omega + t\,\omega^\perp)\,dt. The input is a full scan g[k][j]=g(βk,γj)g[k][j] = g(\beta_k, \gamma_j) with βk=2πk/af\beta_k = 2\pi k/a_f for k=0,…,af−1k = 0, \ldots, a_f - 1 and an equiangular detector γj=(j−(df−1)/2)α\gamma_j = (j - (d_f-1)/2)\alpha. A flat detector at tj=(j−(df−1)/2)τft_j = (j - (d_f-1)/2)\tau_f through the center has the fan angle arctan⁡(tj/D)\arctan(t_j/D).

The output is the parallel sinogram P[k][j]≈Rf(θk,sj)P[k][j] \approx \mathcal{R}f(\theta_k, s_j) with θk=kπ/a\theta_k = k\pi/a for k=0,…,a−1k = 0, \ldots, a - 1 and sj=(j−(d−1)/2)τs_j = (j - (d-1)/2)\tau. The reconstruction after it is an n×nn \times n image on [−1,1]2[-1, 1]^2, with pixel (i,j)(i, j) centered at xj=−1+(2j+1)/nx_j = -1 + (2j+1)/n and yi=1−(2i+1)/ny_i = 1 - (2i+1)/n.

Inverting θ=β+γ\theta = \beta + \gamma and s=Dsin⁡γs = D\sin\gamma gives

γ=arcsin⁡(s/D),β=θ−γ(mod2π).\gamma = \arcsin(s/D), \qquad \beta = \theta - \gamma \pmod{2\pi}.

The algorithm

  1. REBIN(g, D, α, a, d, τ) ▷ g[k][j]: β_k = 2πk/a_f, γ_j = (j - (d_f-1)/2) α
  2. 1a_f, d_f ← the number of rows and of columns of g
  3. 2for k ← 0 to a - 1 do
  4. 3θ ← kπ/a
  5. 4for j ← 0 to d - 1 do
  6. 5s ← (j - (d-1)/2) τ
  7. 6γ ← arcsin(s/D); β ← (θ - γ) mod 2π
  8. 7u ← β a_f/(2π); v ← γ/α + (d_f-1)/2
  9. 8P[k][j] ← BILINEAR(g, u, v) ▷ periodic in u, zero outside the detector in v
  10. 9return P

Line L6 is the inverse map above. Line L7 turns (β,γ)(\beta, \gamma) into fractional indices into the fan data. For a flat detector, line L7 uses v=Dtan⁡γ/τf+(df−1)/2v = D\tan\gamma/\tau_f + (d_f-1)/2. Line L8 reads the four nearest samples. The rows wrap around, because row afa_f would be row 0 again.

A full scan holds each line twice: (θ,s)(\theta, s) and (θ+π,−s)(\theta + \pi, -s). The ray (β,γ)(\beta, \gamma) and the ray (β+π+2γ,−γ)(\beta + \pi + 2\gamma, -\gamma) are the same line. An option of the code takes the mean of the two interpolated copies. This changes nothing for exact data and halves the variance of independent noise.

The reconstruction step is plain parallel FBP: filter each row of PP with the Ram-Lak kernel and back-project over [0,π)[0, \pi) with the weight π/a\pi/a.

Example

Take D=2D = 2, a fan scan with af=8a_f = 8 source positions (Δβ=π/4\Delta\beta = \pi/4) and df=9d_f = 9 bins with α=0.1\alpha = 0.1. Rebin the parallel sample θ=0.3\theta = 0.3, s=0.5s = 0.5.

  • Line L6: γ=arcsin⁡(0.25)=0.25268\gamma = \arcsin(0.25) = 0.25268 and β=0.3−0.25268=0.04732\beta = 0.3 - 0.25268 = 0.04732.
  • Line L7: u=0.04732/(π/4)=0.06025u = 0.04732/(\pi/4) = 0.06025 and v=0.25268/0.1+4=6.52680v = 0.25268/0.1 + 4 = 6.52680.
  • Line L8 mixes the source positions 0 and 1 with the weights 0.939750.93975 and 0.060250.06025, and the bins 6 and 7 with the weights 0.473200.47320 and 0.526800.52680.

Let the object be the unit disk with density 1. Its fan data does not depend on β\beta, and the ray with the fan angle γ\gamma has the length 21−4sin⁡2γ2\sqrt{1 - 4\sin^2\gamma} inside the disk. Bin 6 (γ=0.2\gamma = 0.2) holds 1.835341.83534 and bin 7 (γ=0.3\gamma = 0.3) holds 1.613281.61328. The interpolated value is 0.47320⋅1.83534+0.52680⋅1.61328=1.718360.47320 \cdot 1.83534 + 0.52680 \cdot 1.61328 = 1.71836. The true value is 21−0.25=1.732052\sqrt{1 - 0.25} = 1.73205. The error of 0.01370.0137 comes from the linear interpolation across the curved profile.

A larger setup, measured with the code: D=3D = 3, a fan that covers the disk of radius 2\sqrt{2}, af=64a_f = 64, df=49d_f = 49, rebinned to a=32a = 32 angles and d=47d = 47 bins with τ=22/47\tau = 2\sqrt{2}/47, and n=32n = 32. The smooth object is the blob e−4π∣x−c∣2e^{-4\pi\vert x - c\vert^2} with c=(0.3,−0.2)c = (0.3, -0.2). These numbers are measurements of this setup, not bounds.

quantity value
largest error of the rebinned sinogram, blob, equiangular detector 0.0030
same, mean of the two copies 0.0028
same, flat detector 0.0084
largest image error, blob, rebinning and parallel FBP 0.0243
largest image error, blob, parallel FBP on exact parallel data 0.0153
largest error of the rebinned sinogram, modified Shepp-Logan phantom (5 ellipses) 0.114
image value at pixel (16,16)(16, 16) of that phantom, true 0.2 0.2102

The sinogram error of the phantom is large only at the edges of the ellipses, where the profile has a square-root corner that linear interpolation cannot follow.

Correctness

The proof in proofs/correctness.md has three parts. First, for ∣s∣<D|s| < D the map of line L6 gives the only fan ray that is the wanted line, so with exact data at the right points the rebinned sinogram is exact. Second, bilinear interpolation reproduces data of the form c+eγc + e\gamma exactly and has the error at most (Δβ2M1+α2M2)/8(\Delta\beta^2 M_1 + \alpha^2 M_2)/8, where M1M_1 and M2M_2 bound the second derivatives of the fan data in β\beta and γ\gamma. Third, parallel FBP is linear, and its discrete operator has the norm at most π/(2τ)\pi/(2\tau) in the maximum norm. So the rebinning error adds at most π/(2τ)\pi/(2\tau) times the largest sinogram error to the image, on top of the error of parallel FBP.

Proof: Correctness of fan-to-parallel rebinningfull

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 p(θ,s)=Rf(θ,s)=∫f(s ω+t ω⊥) dtp(\theta, s) = \mathcal{R}f(\theta, s) = \int f(s\,\omega + t\,\omega^\perp)\,dt for all real θ\theta, so p(θ+π,−s)=p(θ,s)p(\theta + \pi, -s) = p(\theta, s) and pp has the period 2π2\pi in θ\theta. The source at the angle β\beta is S(β)=D ω⊥(β)S(\beta) = D\,\omega^\perp(\beta), and the fan data is g(β,γ)=p(β+γ,Dsin⁡γ)g(\beta, \gamma) = p(\beta + \gamma, D\sin\gamma) for ∣γ∣<π/2|\gamma| < \pi/2.

The proof has three parts. Part 1 shows that the map of line L6 finds a fan ray that is the wanted parallel ray, so with exact interpolation the rebinned sinogram is exact. Part 2 bounds the error of the bilinear interpolation of line L8 and proves that it is exact on data that is linear in the fan angle and does not depend on the source angle. Part 3 joins the result with the correctness of parallel-beam filtered back-projection.

Part 1. The rebinning map

Lemma 1. Let ∣s∣<D|s| < D and θ∈R\theta \in \mathbb{R}. Put γ=arcsin⁡(s/D)\gamma = \arcsin(s/D) and β=θ−γ\beta = \theta - \gamma, reduced modulo 2π2\pi. Then g(β,γ)=p(θ,s)g(\beta, \gamma) = p(\theta, s). The pair (β,γ)(\beta, \gamma) with β∈[0,2π)\beta \in [0, 2\pi) and ∣γ∣<π/2|\gamma| < \pi/2 is the only fan ray that is the oriented line (θ,s)(\theta, s). The fan ray (β+π+2γ,−γ)(\beta + \pi + 2\gamma, -\gamma) is the same line with the other orientation, (θ+π,−s)(\theta + \pi, -s).

Proof. By definition g(β,γ)=p(β+γ,Dsin⁡γ)=p(θ−2πm,s)g(\beta, \gamma) = p(\beta + \gamma, D\sin\gamma) = p(\theta - 2\pi m, s) for some integer mm, and pp has the period 2π2\pi in θ\theta. For uniqueness, Dsin⁡γ=sD\sin\gamma = s has the single solution γ=arcsin⁡(s/D)\gamma = \arcsin(s/D) in (−π/2,π/2)(-\pi/2, \pi/2), and then β≡θ−γ\beta \equiv \theta - \gamma modulo 2π2\pi. For the last claim, (β+π+2γ)+(−γ)=θ+π(\beta + \pi + 2\gamma) + (-\gamma) = \theta + \pi and Dsin⁡(−γ)=−sD\sin(-\gamma) = -s. □\square

This is what lines L5 to L7 compute. For a flat detector the column of the ray is t=Dtan⁡γt = D\tan\gamma in place of γ\gamma, and the lemma is the same. With average=True the code takes the mean of the two copies (θ,s)(\theta, s) and (θ+π,−s)(\theta + \pi, -s). By the lemma both copies equal p(θ,s)p(\theta, s) for exact data, so the mean changes nothing for exact data and halves the variance of independent noise in the two readings.

If the fan covers the support of ff, that is, ff is zero outside the disk of radius rr with r≤Dsin⁡γmax⁡r \le D\sin\gamma_{\max} where γmax⁡=(d−1)α/2\gamma_{\max} = (d-1)\alpha/2, then every parallel sample with ∣s∣>r|s| > r is 0, and the samples with ∣s∣≤r|s| \le r map to fan angles inside the detector.

Part 2. Bilinear interpolation

Line L8 reads the fan data g[k][j]=g(βk,γj)g[k][j] = g(\beta_k, \gamma_j) at the fractional indices u=β/Δβu = \beta/\Delta\beta and v=γ/α+(d−1)/2v = \gamma/\alpha + (d-1)/2, where Δβ=2π/a\Delta\beta = 2\pi/a. The rows are periodic: row aa is row 0. This matches the period 2π2\pi of gg in β\beta.

Lemma 2 (exact cases). If g(β,γ)=c+eγg(\beta, \gamma) = c + e\gamma for constants cc and ee, then line L8 returns c+eγc + e\gamma at each point with 0≤v≤d−10 \le v \le d - 1.

Proof. The value does not depend on kk, and the two row weights 1−wu1 - w_u and wuw_u add to 1, so the result is the linear interpolation in jj. Linear interpolation between c+eγj0c + e\gamma_{j_0} and c+eγj0+1c + e\gamma_{j_0 + 1} at the fraction wvw_v gives c+e(γj0+wvα)=c+eγc + e(\gamma_{j_0} + w_v\alpha) = c + e\gamma. □\square

So for such data the rebinned value at (θ,s)(\theta, s) is exactly c+earcsin⁡(s/D)c + e\arcsin(s/D), which the test checks.

Lemma 3 (error bound). Let gg be C2C^2 on the cell [βk,βk+1]×[γj,γj+1][\beta_k, \beta_{k+1}] \times [\gamma_j, \gamma_{j+1}], with ∣∂β2g∣≤M1|\partial_\beta^2 g| \le M_1 and ∣∂γ2g∣≤M2|\partial_\gamma^2 g| \le M_2 there. Then at each point of the cell the bilinear interpolant IgI g satisfies

∣g−Ig∣≤Δβ28M1+α28M2.|g - I g| \le \frac{\Delta\beta^2}{8}M_1 + \frac{\alpha^2}{8}M_2.

Proof. Let IβI_\beta be linear interpolation in β\beta at a fixed γ\gamma, and IγI_\gamma linear interpolation in γ\gamma at a fixed β\beta. Then I=IγIβI = I_\gamma I_\beta and g−Ig=(g−Iγg)+Iγ(g−Iβg)g - Ig = (g - I_\gamma g) + I_\gamma(g - I_\beta g). The 1D error of linear interpolation on an interval of length ℓ\ell is at most ℓ2max⁡∣q′′∣/8\ell^2\max|q''|/8, since q−Iqq - Iq vanishes at both ends and equals −12q′′(ξ)(x−x0)(x1−x)-\frac{1}{2}q''(\xi)(x - x_0)(x_1 - x) for some ξ\xi, and (x−x0)(x1−x)≤ℓ2/4(x - x_0)(x_1 - x) \le \ell^2/4. So ∣g−Iγg∣≤α2M2/8|g - I_\gamma g| \le \alpha^2 M_2/8. The function g−Iβgg - I_\beta g is at most Δβ2M1/8\Delta\beta^2 M_1/8 at both nodes in γ\gamma, and IγI_\gamma is a convex combination of these node values. □\square

For a smooth ff the fan data is smooth, and the rebinned sinogram has the error O(Δβ2+α2)O(\Delta\beta^2 + \alpha^2). At the edge of an object of constant density, pp has a square-root singularity in ss, the second derivative is not bounded, and the bound does not hold. The measured errors at such edges on the page are much larger than in the smooth case.

Part 3. The reconstruction

Let PP be the rebinned sinogram and P⋆P^\star the exact parallel sinogram on the same grid. Parallel-beam FBP is linear, so its output on PP is its output on P⋆P^\star plus its output on P−P⋆P - P^\star. The first term is analyzed on the page filtered back-projection, whose proof shows that the method is exact for band-limited data up to the angular quadrature and the linear interpolation of the back-projection. The second term is bounded by the norm of the discrete FBP operator times max⁡∣P−P⋆∣\max|P - P^\star|. The discrete operator is a fixed linear map. Its norm in the maximum norm is at most (π/ap) ap τ∑m∣h(mτ)∣≤π τ (1/(4τ2)+2∑m odd1/(m2π2τ2))=π/(2τ)(\pi/a_p)\,a_p\,\tau\sum_m |h(m\tau)| \le \pi\,\tau\,(1/(4\tau^2) + 2\sum_{m \text{ odd}} 1/(m^2\pi^2\tau^2)) = \pi/(2\tau), using ∑m≥1, m odd1/m2=π2/8\sum_{m \ge 1,\ m \text{ odd}} 1/m^2 = \pi^2/8. So the error that the interpolation adds to the image is at most π/(2τ)\pi/(2\tau) times the largest rebinning error. The bound grows as the detector spacing shrinks, which is the usual amplification of data errors by the ramp filter.

With the values of the test, τ=22/47=0.0602\tau = 2\sqrt{2}/47 = 0.0602 and the largest rebinning error on the smooth blob is 0.00300.0030, so the bound is 0.0790.079. In the measurement on the page, the largest image error grows from 0.01530.0153 for exact parallel data to 0.02430.0243 after rebinning, a change of 0.0090.009, well below the bound.

Complexity

In the real-RAM model, lines L5 to L8 take O(1)O(1) time for each of the ada d parallel samples, so rebinning takes O(ad)O(a d) time and O(ad)O(a d) space for the output. The fan data is read but not copied. The parallel FBP after it takes O(adlog⁡d+an2)O(a d \log d + a n^2) with an FFT, or O(ad2+an2)O(a d^2 + a n^2) with the direct sum that the code uses. Rebinning is cheap next to the reconstruction.

Properties

  • Linear. The output is a fixed linear combination of the input, with at most 4 nonzero weights per output sample (8 with the mean of two copies).
  • Exact map, approximate values. The geometry is exact. The only error is the interpolation, which is second order for smooth data.
  • Smoothing. Linear interpolation is a low-pass filter. It reduces the resolution a little and correlates the noise of neighboring samples.
  • Detector independence. The parallel method after it does not need to know anything about the fan geometry.

Variants and improvements

  • Direct fan-beam FBP. Fan-beam filtered back-projection avoids the interpolation before the filter, at the cost of a distance weight in the back-projection.
  • Better interpolation. Cubic or windowed sinc interpolation in γ\gamma reduces the smoothing. Interpolation in β\beta matters less when the source angles are dense.
  • Two separate steps. Each parallel angle mixes rays from many source angles, but for a fixed fan angle the map β=θ−γ\beta = \theta - \gamma is a shift. Some codes interpolate first in β\beta for each fan angle, then in ss for each parallel angle.
  • Short scans. Data over π\pi plus the fan angle also fills the parallel sinogram over [0,π)[0, \pi). Each line then exists at least once, and the code needs the copy rule to find it.
  • Cone beam. Rebinning the rows of a helical cone-beam scan to parallel fans is a step of several practical helical methods. The exact helical method on this site is Katsevich's algorithm.

When to use it

Use rebinning when a good parallel-beam code is at hand and the fan data is dense, so the interpolation error is small. It also helps when a method needs parallel data, such as direct Fourier reconstruction or a method that uses the parallel range conditions. When the source angles are sparse, the interpolation in β\beta is coarse, and direct fan-beam FBP is better.

Pitfalls

  • The wrong sign of the fan angle. With the other sign convention for γ\gamma, line L6 must use β=θ+γ\beta = \theta + \gamma. Test the map on a point object at a known place, as the test of the code does with θ=β+γ\theta = \beta + \gamma and s=Dsin⁡γs = D\sin\gamma.
  • No wrap in β\beta. The source angle is periodic. A sample with β\beta between the last source and 2π2\pi must mix the last row with row 0.
  • Parallel bins outside the fan. If ∣s∣≥Dsin⁡γmax⁡|s| \ge D\sin\gamma_{\max}, the line is not in the data. The code returns 0, which is right only if the object lies inside the fan.
  • Offsets in the detector. A shift of the central ray by a fraction of a bin moves every rebinned sample and blurs the image.

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.

fan_to_parallel_rebinning.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fan-to-parallel-rebinning/. The authors are listed in prov/D52MD2.jsonl.
"""Fan-to-parallel rebinning, followed by parallel-beam filtered back-projection.

Conventions:
- omega(t) = (cos t, sin t) and omega_perp(t) = (-sin t, cos t). The Radon
  transform is R f(theta, s) = integral f(s omega(theta) + t omega_perp(theta)) dt.
- The source at angle beta is S(beta) = D omega_perp(beta). The ray at the fan
  angle gamma is the line with theta = beta + gamma and s = D sin gamma, so the
  fan data is g(beta, gamma) = R f(beta + gamma, D sin gamma).
- Fan data: a full scan, beta_k = 2 pi k / a for k = 0 .. a - 1, and either an
  equiangular detector, gamma_j = (j - (d - 1) / 2) alpha, or a flat virtual
  detector through the center, t_j = (j - (d - 1) / 2) tau_f, with the fan angle
  atan(t_j / D).
- Parallel data: theta_k = k pi / a_p for k = 0 .. a_p - 1 and
  s_j = (j - (d_p - 1) / 2) tau for j = 0 .. d_p - 1.
- The output image is n x n on [-1, 1]^2, pixel (i, j) centered at
  x_j = -1 + (2 j + 1) / n and y_i = 1 - (2 i + 1) / n.
"""

import math


def fan_coordinates(theta, s, dist):
    """(beta, gamma) of the line (theta, s): gamma = asin(s / D), beta = theta - gamma mod 2 pi."""
    gamma = math.asin(s / dist)
    return (theta - gamma) % (2.0 * math.pi), gamma


def bilinear(g, u, v):
    """Interpolate g[k][j] at the fractional indices (u, v): periodic in k, zero outside in j."""
    a, d = len(g), len(g[0])
    k0 = math.floor(u)
    wu = u - k0
    j0 = math.floor(v)
    wv = v - j0
    val = 0.0
    for dk, fu in ((0, 1.0 - wu), (1, wu)):
        if fu == 0.0:
            continue
        row = g[(k0 + dk) % a]
        for dj, fv in ((0, 1.0 - wv), (1, wv)):
            j = j0 + dj
            if fv != 0.0 and 0 <= j < d:
                val += fu * fv * row[j]
    return val


def rebin(g, dist, alpha, a_p, d_p, tau, detector="equiangular", average=False):
    """Parallel sinogram P[k][j] ~ R f(theta_k, s_j) from full-scan fan data g.

    alpha is the angle step of an equiangular detector, or the spacing tau_f of
    a flat detector. With average=True each parallel sample is the mean of its
    two copies in the full scan, (theta, s) and (theta + pi, -s).
    """
    a, d = len(g), len(g[0])  # @line L1
    dbeta = 2.0 * math.pi / a
    c0 = (d - 1) / 2.0

    def sample(theta, s):
        beta, gamma = fan_coordinates(theta, s, dist)  # @line L6
        if detector == "equiangular":
            v = gamma / alpha + c0  # @line L7
        else:
            v = dist * math.tan(gamma) / alpha + c0
        return bilinear(g, beta / dbeta, v)  # @line L8

    out = []
    for k in range(a_p):  # @line L2
        theta = k * math.pi / a_p  # @line L3
        row = []
        for j in range(d_p):  # @line L4
            s = (j - (d_p - 1) / 2.0) * tau  # @line L5
            val = sample(theta, s)
            if average:
                val = 0.5 * (val + sample(theta + math.pi, -s))
            row.append(val)
        out.append(row)
    return out  # @line L9


def ram_lak_kernel(d, tau):
    """h(m tau), m = -(d - 1) .. d - 1, of the ramp filter band-limited to 1 / (2 tau)."""
    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 parallel_fbp(sino, tau, n):
    """Parallel-beam FBP on [0, pi) with the Ram-Lak kernel and a direct convolution."""
    a, d = len(sino), len(sino[0])
    h = ram_lak_kernel(d, tau)
    c0 = (d - 1) / 2.0
    qs = [[tau * sum(h[j - l + d - 1] * p[l] for l in range(d)) for j in range(d)] for p in sino]
    xs = [-1.0 + (2 * j + 1) / n for j in range(n)]
    ys = [1.0 - (2 * i + 1) / n for i in range(n)]
    img = [[0.0] * n for _ in range(n)]
    for k, q in enumerate(qs):
        c, s = math.cos(k * math.pi / a), math.sin(k * math.pi / a)
        for i, y in enumerate(ys):
            row = img[i]
            for j, x in enumerate(xs):
                u = (x * c + y * s) / tau + c0
                b = math.floor(u)
                w = u - b
                if 0 <= b < d:
                    row[j] += (1.0 - w) * q[b]
                if 0 <= b + 1 < d:
                    row[j] += w * q[b + 1]
    return [[math.pi / a * v for v in row] for row in img]


def rebin_and_reconstruct(g, dist, alpha, a_p, d_p, tau, n, detector="equiangular", average=False):
    """Rebin the fan data, then reconstruct with parallel-beam FBP."""
    return parallel_fbp(rebin(g, dist, alpha, a_p, d_p, tau, detector, average), tau, n)
test_fan_to_parallel_rebinning.py 128 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fan-to-parallel-rebinning/. The authors are listed in prov/D52MD2.jsonl.

import math
import random

from fan_to_parallel_rebinning import (
    bilinear,
    fan_coordinates,
    parallel_fbp,
    ram_lak_kernel,
    rebin,
    rebin_and_reconstruct,
)

DIST = 3.0
GAMMA_MAX = math.asin(math.sqrt(2.0) / DIST)  # the fan covers the disk of radius sqrt(2)
D = 49
ALPHA = 2.0 * GAMMA_MAX / (D - 1)
TAU_FLAT = 2.0 * DIST * math.tan(GAMMA_MAX) / (D - 1)
A = 64
AP, DP = 32, 47
TAU = 2.0 * math.sqrt(2.0) / DP
N = 32
XS = [-1.0 + (2 * j + 1) / N for j in range(N)]
YS = [1.0 - (2 * i + 1) / N for i in range(N)]
EQUI = [(j - (D - 1) / 2.0) * ALPHA for j in range(D)]
FLAT = [math.atan((j - (D - 1) / 2.0) * TAU_FLAT / DIST) for j in range(D)]
BETAS = [2.0 * math.pi * k / A for k in range(A)]

PHANTOM = [
    (1.0, 0.69, 0.92, 0.0, 0.0, 0.0),
    (-0.8, 0.6624, 0.874, 0.0, -0.0184, 0.0),
    (-0.2, 0.11, 0.31, 0.22, 0.0, -18.0),
    (-0.2, 0.16, 0.41, -0.22, 0.0, 18.0),
    (0.1, 0.21, 0.25, 0.0, 0.35, 0.0),
]


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 blob_projection(theta, s):
    """R f for f(x) = exp(-4 pi |x - c|^2) with c = (0.3, -0.2)."""
    u = s - (0.3 * math.cos(theta) - 0.2 * math.sin(theta))
    return 0.5 * math.exp(-4.0 * math.pi * u * u)


def fan_data(radon, gammas):
    return [[radon(b + g, DIST * math.sin(g)) for g in gammas] for b in BETAS]


def parallel_data(radon):
    return [[radon(k * math.pi / AP, (j - (DP - 1) / 2.0) * TAU) for j in range(DP)] for k in range(AP)]


def blob_error(img):
    return max(
        abs(img[i][j] - math.exp(-4.0 * math.pi * ((XS[j] - 0.3) ** 2 + (YS[i] + 0.2) ** 2)))
        for i in range(N)
        for j in range(N)
    )


def test_fan_coordinates() -> None:
    beta, gamma = fan_coordinates(0.3, 0.5, 2.0)
    assert abs(gamma - 0.25268) < 1e-5 and abs(beta - 0.04732) < 1e-5
    rng = random.Random(1)
    for _ in range(200):
        theta, s = rng.uniform(0, math.pi), rng.uniform(-1.4, 1.4)
        beta, gamma = fan_coordinates(theta, s, DIST)
        assert 0.0 <= beta < 2.0 * math.pi
        assert abs(math.sin(beta + gamma - theta)) < 1e-12 and math.cos(beta + gamma - theta) > 0
        assert abs(DIST * math.sin(gamma) - s) < 1e-12


def test_bilinear_is_periodic_in_the_angle() -> None:
    g = [[1.0, 2.0], [3.0, 4.0]]
    assert bilinear(g, 0.5, 0.5) == 2.5
    assert bilinear(g, 1.5, 0.0) == 2.0  # half way between row 1 and row 0
    assert bilinear(g, 0.0, 1.5) == 1.0  # half way between column 1 and nothing


def test_exact_on_data_linear_in_the_fan_angle() -> None:
    # g = c + e gamma is reproduced by the interpolation, so the result is c + e asin(s / D)
    g = [[0.7 + 2.0 * gm for gm in EQUI] for _ in BETAS]
    p = rebin(g, DIST, ALPHA, AP, DP, TAU)
    for k in range(AP):
        for j in range(DP):
            s = (j - (DP - 1) / 2.0) * TAU
            if abs(s) <= DIST * math.sin(GAMMA_MAX) - 1e-9:
                assert abs(p[k][j] - (0.7 + 2.0 * math.asin(s / DIST))) < 1e-12


def test_rebinned_sinogram_is_close() -> None:
    want = parallel_data(blob_projection)
    for det, gammas, step in (("equiangular", EQUI, ALPHA), ("flat", FLAT, TAU_FLAT)):
        for avg in (False, True):
            p = rebin(fan_data(blob_projection, gammas), DIST, step, AP, DP, TAU, detector=det, average=avg)
            assert max(abs(p[k][j] - want[k][j]) for k in range(AP) for j in range(DP)) < 0.02


def test_reconstruction_of_a_blob() -> None:
    img = rebin_and_reconstruct(fan_data(blob_projection, EQUI), DIST, ALPHA, AP, DP, TAU, N)
    assert blob_error(img) < 0.03
    direct = parallel_fbp(parallel_data(blob_projection), TAU, N)
    assert blob_error(direct) < 0.03


def test_phantom_values() -> None:
    radon = lambda t, s: ellipse_projection(PHANTOM, t, s)
    img = rebin_and_reconstruct(fan_data(radon, EQUI), DIST, ALPHA, AP, DP, TAU, N, average=True)
    assert abs(img[16][16] - 0.2) < 0.04
    assert abs(img[8][16] - 0.3) < 0.05


def test_ram_lak_kernel() -> None:
    h = ram_lak_kernel(3, 0.5)
    assert h[2] == 1.0 and h[1] == h[3] == -4.0 / math.pi ** 2 and h[0] == h[4] == 0.0

History

The first CT scanners used parallel translate and rotate motions, and fan-beam scanners came soon after. Reordering the fan rays into parallel projections was the natural first way to reuse the parallel methods. Herman, Lakshminarayanan and Naparstek gave in 1976 a convolution method on the fan data directly. Kak and Slaney treat the re-sorting algorithm and the direct methods side by side in their Section 3.4.

References

  1. A. C. Kak and M. Slaney, Principles of Computerized Tomographic Imaging, SIAM Classics in Applied Mathematics 33, 2001, Chapter 3, Section 3.4 (reconstruction from fan projections, the subsection on a re-sorting algorithm) and Section 3.3 (parallel projections)
  2. G. T. Herman, A. V. Lakshminarayanan and A. Naparstek, Convolution reconstruction techniques for divergent beams, Computers in Biology and Medicine 6(4), 1976, pp. 259 to 271 (the direct method that rebinning competes with)

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
  • History with a source
  • at least three sources
  • a scene preset for the example