Algorithmcore
Direct Fourier reconstruction
Also called Fourier reconstruction for tomography.
Reconstruct a CT slice from the 1D transforms of its projections. Place them on radial lines, interpolate onto a Cartesian grid and take an inverse 2D FFT.
- Time
- O(a d log d + n^2 log n) 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
- R. N. Bracewell, 1956
Direct Fourier reconstruction solves the tomographic reconstruction problem in the Fourier domain. By the Fourier slice theorem, the 1D Fourier transform of each projection in the sinogram gives the 2D Fourier transform of the image on one line through the origin. The method computes these lines with the fast Fourier transform, interpolates the values from the polar grid onto a Cartesian grid, and takes one inverse 2D FFT. With angles, detector bins and an image it takes time. The interpolation step is its weak point, and filtered back-projection usually gives better images at a higher cost.
In plain words
Each projection of the object tells you one line of the object's frequency picture. If you take the projections at many angles, you get many lines through the center of the frequency plane, like the spokes of a wheel. When you know the whole frequency plane, one inverse transform gives back the object.
The fast inverse transform needs the values on a square grid, but the spokes give them on circles and rays. So the method estimates each grid value from the nearest spoke values. Near the center the spokes are close together and the estimate is good. Far from the center the spokes spread apart, and the estimates of the fine detail get worse.
The problem
The data is a sinogram for and . Row samples the projection of the Radon transform of an unknown image at the angle . Bin has its center at , with the detector spacing . The output is an image on , with even. Pixel has its center at and , so the pixel size is .
The Fourier transform uses ordinary frequency, . The Fourier slice theorem then reads , with and no other constant.
The algorithm
DFR(P, τ, n) ▷ P[k][j]: angle θ_k = kπ/a, bin center s_j = (j - (d-1)/2) τ- 1
a, d ← the size of P; L ← the smallest power of 2 with L ≥ 4d; N ← 2n; Δξ ← 1/(N h) with h = 2/n - 2
for k ← 0 to a - 1 do - 3
S_k[l] ← τ e^{2πi τ σ_l (d-1)/2} · DFT_L(P[k] padded with zeros to L)[l], with σ_l = l/(Lτ) signed - 4
for u, v ← -N/2 .. N/2 - 1 do - 5
(θ, σ) ← the angle in [0, π) and the signed radius with σ ω(θ) = (u, v) Δξ - 6
F ← 0 if |σ| > 1/(2τ), else the bilinear interpolation of S in (θ, σ) - 7
G[v mod N][u mod N] ← F e^{πi(u+v)/N} Δξ² - 8
g ← N² IDFT2_N(G) - 9
return f[i][j] = Re g[(n/2 - 1 - i) mod N][(j - n/2) mod N]
Line L3 turns each projection into samples of on the radial line at the angle . The factor makes the DFT a Riemann sum of the Fourier integral. The phase factor moves the origin of the detector from bin 0 to the bin position . The signed frequency is for and otherwise. The padding to does not add information, but it makes the radial samples four times denser, so the radial interpolation of line L6 is more accurate.
Lines L4 to L7 fill the Cartesian grid. Line L5 folds each frequency into the half plane of the data: a point with a negative polar angle has and a negative radius. Line L6 interpolates linearly between the two nearest angles and, on each of them, between the two nearest radial samples. The angle is not in the data, so the upper neighbor of the last angle is the angle 0 with the radius negated. The factor in line L7 is a shift by half a pixel, because the pixel centers lie between the points of the DFT grid. Lines L8 and L9 then evaluate the inverse Fourier integral at the pixel centers by one inverse 2D DFT (a multidimensional FFT). The grid has points per axis, so the image repeats with the period , which is twice the side of the square. The copies of the image do not overlap it.
Example
Take the Gaussian . Its projection is at each angle, and its transform is . Use angles, bins, and . Then , the radial spacing is , the band edge is , and the grid has and , so it reaches the frequency 8.
Follow the grid point , which is :
| step | value |
|---|---|
| radius and polar angle | 2.2361 and 0.46365 rad |
| angle index | 4.7227, between the angles 4 and 5 |
| radial index | 34.449, between the samples 34 and 35 |
| and (the same at the angle 5) | 0.0054526 and 0.0043395 |
| interpolated value | 0.0049532 |
| true value | 0.0049257 |
The spectrum is radial, so the two angles give the same values and only the radial interpolation makes an error, here 0.6 percent. The spectrum is convex in the radius there, so the chord lies above the curve. At this radius the arc between two angles is , more than three times the radial spacing. For an image without radial symmetry, the angular interpolation is the larger error.
The table gives the error of the code below on analytic projections in the same setup. The FBP column is filtered back-projection with the Ram-Lak kernel on the same data. These numbers are measurements of this setup, not bounds.
| phantom | DFR, bilinear | DFR, nearest | FBP |
|---|---|---|---|
| Gaussian , largest error | 0.0005 | 0.0033 | 0.0170 |
| disk of radius , largest error for | 0.0125 | 0.0242 | 0.0098 |
| Shepp-Logan phantom, largest error for | 0.072 | 0.184 | |
| Shepp-Logan phantom, value at pixel , true 1.02 | 1.048 | 1.054 | 1.0217 |
On the smooth Gaussian the method is better than FBP, because the spectrum is smooth and the interpolation is accurate. On the disk and the phantom, whose spectra oscillate, it is worse, and the errors spread over the whole image.
Correctness
The proof in proofs/correctness.md treats the three stages. First, if each projection is band-limited to and zero outside the detector, the scaled and phase-shifted DFT of line L3 equals on the radial line, by the Fourier slice theorem and the sampling theorem. Second, the inverse DFT of lines L7 to L9 equals, at each pixel center, the Riemann sum . Third, with the exact spectrum on the whole lattice, this sum is the Fourier series of the periodized image, and it equals on because the period 4 is larger than the support. So the only approximations are the interpolation of line L6 and the truncation of the spectrum to the box and the band.
Proof: Correctness of direct Fourier reconstructionfull
We use the conventions of the page. , for , and . The image has the pixel size with even, and pixel has its center at and . The Cartesian grid has points on each axis and the spacing .
The proof has three parts, one for each stage of the algorithm. Lines L2 and L3 give exact samples of on the polar grid when the projections are band-limited (Lemma 1). Lines L8 and L9 give the exact Riemann sum of the inverse Fourier integral at the pixel centers, and that sum equals when the spectrum is known on the whole lattice (Lemmas 2 and 3). Lines L4 to L7 connect the two grids by interpolation, which is the main approximation of the method.
Lemma 1 (the polar samples). Let . Fix and put and . Assume that is continuous, that its transform vanishes for , and that for every with or . Then for every with signed frequency , where for and otherwise,
Proof. Because is an integer and , we have . So , and the terms with outside are zero by assumption. Let , so that and . The function is continuous, vanishes outside with , and its periodic extension with period has the Fourier coefficients . As in the proof for filtered back-projection, this gives for , where the sum has finitely many terms. Hence for , and the Fourier slice theorem gives . Line L3 computes the left side, because the DFT of the zero-padded projection is .
The lemma holds for every . The choice in line L1 does not change the samples. It makes the radial grid four times finer than the natural spacing , which reduces the error of the radial interpolation in line L6.
Lemma 2 (the grid to the image). Let be any function on the lattice and let for , as in line L7. Let , as in line L8. Then for each pixel , with and ,
Proof. By the definition of the inverse 2D DFT, . Each pair is for exactly one pair in the centered range, and because the two exponents differ by a multiple of . The same holds for in place of . So
Now and , and . So and .
Line L9 takes the real part. For a real the full lattice sum is real, because . The truncated sum of Lemma 2 is real as well when the spectrum array is Hermitian; the interpolation of lines L5 and L6 keeps this property, because the value at is read from the same samples at the same weights with the radius negated, and of a real projection satisfies . The real part then removes only rounding errors.
Lemma 3 (the lattice sum is the image). Let be continuous with support in , and assume that . If , then for every
Proof. Let and let be the periodization of with period in each coordinate. Since , at most one term is nonzero at each point, so is continuous. Its Fourier coefficient for the frequency is . By assumption these coefficients are absolutely summable, so the Fourier series of converges uniformly to . For and , the point has a coordinate of absolute value more than , so and .
With the period is , so the copies of the image in Lemma 3 do not overlap the square . With the period would be 2, and the copies of an object that fills the square would touch it.
The errors that remain. Lemmas 1 to 3 show that the output equals at the pixel centers when three conditions hold: the projections are band-limited and zero outside the detector (Lemma 1), the spectrum outside the box is zero (Lemma 2 sums only over the box), and the values on the Cartesian lattice are exact. Lines L5 and L6 do not give exact values: they interpolate bilinearly in the angle and the signed radius between the four nearest polar samples. On a polar grid the angular step at the radius is , so the interpolation error grows with the frequency. For a radial spectrum, such as that of a centered Gaussian, the angular part of the interpolation is exact and only the radial part remains. An object with sharp edges has a spectrum that oscillates in the angle as well as in the radius, and the interpolation error then spreads over the whole image, because one wrong value in the Fourier plane changes every pixel. This is the reason for the gridding methods of the variants.
The interpolation step is well defined. Line L5 maps with to for and to for , and goes to . In each case and . The upper angle neighbor of is the angle , which is not a row of the sinogram. Line L6 reads it as the row of the angle 0 at the radius , because . So the interpolated value is continuous across the negative axis.
Complexity
In the real-RAM model with an FFT:
- Lines L2 and L3 take FFTs of length , so .
- Lines L4 to L7 take for each of the grid points, so .
- Line L8 is an inverse 2D FFT of size , so .
The total is time and extra space. In the usual case this is , against for filtered back-projection. With a direct DFT in place of the FFT, line L8 takes and lines L2 and L3 take .
Properties
- Linear. The output is a linear function of the sinogram, because each step is linear.
- One inverse transform. The whole image comes from one 2D FFT. The cost does not grow with the product of the number of angles and the number of pixels, as it does for back projection.
- Global errors. An error at one frequency changes every pixel by a plane wave. So the interpolation error is not local, unlike the error of the linear interpolation in back projection.
- Accurate at low frequencies. The polar samples are dense near the origin and sparse at the band edge. The low frequencies, which hold the mean values of large regions, come out well, and the fine detail is the least accurate.
- Real output. The interpolation reads the values at and from the same samples with the same weights, so the grid spectrum is Hermitian and the inverse transform is real up to rounding.
Variants and improvements
- Better interpolation. Nearest-neighbor interpolation is the cheapest and the worst. Bilinear interpolation in the angle and the radius, as in line L6, is a good default. Stark, Woods, Paul and Hingorani studied interpolation methods that make this error smaller, and Kak and Slaney refer to their paper for such methods (Section 3.7). An exact recovery from samples on radial lines is possible in theory, but it leads to badly conditioned systems (Kak and Slaney, Section 3.2).
- Gridding. O'Sullivan convolved each polar sample with a small kernel onto the Cartesian grid, with weights for the sample density, and divided the image by the transform of the kernel at the end. This is the gridding method of MRI. See density compensation.
- Nonuniform FFT. A nonuniform FFT evaluates the inverse transform of the polar samples directly, with a controlled error and at about the cost of an FFT.
- Oversampling. A larger in line L1 or a larger grid factor in place of reduces the interpolation error at the cost of more memory.
- Other fields. The same polar-to-Cartesian step appears in the polar format algorithm of radar imaging and in single-particle reconstruction of electron microscopy, where the data are 2D slices of a 3D spectrum.
When to use it
Use direct Fourier reconstruction when speed matters more than image quality, when the image is large and the projections are many, or when the object is smooth. It is also the natural route when the data come in the Fourier domain, as in MRI and radar. For sharp edges and fine detail at the same cost scale, prefer filtered back-projection, which interpolates in space, where linear interpolation is accurate. For dense polar data the sampling rule of filtered back-projection applies here too: with fewer angles, the outer ring of the Fourier plane has gaps that no interpolation fills.
Pitfalls
- Nearest-neighbor artifacts. Rounding each grid point to the nearest polar sample gives errors that the inverse transform spreads over the whole image as streaks and rings. In the table above it more than doubles the error inside the phantom.
- Sparse outer samples. The arc between two angles grows with the radius. At the band edge it is , so too few angles leave the high frequencies to guesswork.
- The angle wrap. The data cover , so the grid points with a negative polar angle need and a negative radius, and the points just below the angle need the angle 0 with the radius negated. Without this, the interpolation jumps across the negative axis.
- The missing phase. The DFT treats bin 0 as the origin, but the center of rotation is at bin . Without the phase factor of line L3 each projection moves by , and the image is wrong. Without the half-pixel factor of line L7 the image moves by half a pixel.
- Too small a grid. With the period of the image equals the side of the square. Then the edges of the object wrap to the opposite side.
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/direct-fourier-reconstruction/. The authors are listed in prov/1BAE5C.jsonl.
"""Direct Fourier reconstruction 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 Fourier transform uses ordinary frequency:
F f(xi) = integral f(x) exp(-2 pi i x . xi) dx. By the Fourier slice
theorem, the 1D transform of the projection at angle theta is
F f(sigma (cos theta, sin theta)).
- The output is an n x n image on [-1, 1]^2, n even. 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 cmath
import math
from imgkit import dft, idft2
def _pow2_at_least(m):
length = 1
while length < m:
length *= 2
return length
def polar_spectra(sino, tau, over=4):
"""The 1D transforms of the projections on the radial grid sigma_l = l / (L tau).
Returns (spectra, L). spectra[k][l] approximates F f(sigma_l omega(theta_k)),
with l < L / 2 for frequency l and l >= L / 2 for frequency l - L.
"""
a, d = len(sino), len(sino[0])
length = _pow2_at_least(over * d)
c0 = (d - 1) / 2.0
spectra = []
for k in range(a): # @line L2
pf = dft(list(sino[k]) + [0.0] * (length - d))
row = []
for l in range(length):
sigma = (l if l < length // 2 else l - length) / (length * tau)
row.append(tau * pf[l] * cmath.exp(2j * math.pi * c0 * tau * sigma)) # @line L3
spectra.append(row)
return spectra, length
def _radial(row, length, r):
"""Linear interpolation of a spectrum row at the signed fractional index r, 0 off the grid."""
r0 = math.floor(r)
w = r - r0
val = 0j
for idx, wt in ((r0, 1.0 - w), (r0 + 1, w)):
if wt != 0.0 and -length // 2 <= idx < length // 2:
val += wt * row[idx % length]
return val
def polar_value(spectra, length, tau, xi_x, xi_y, interp="linear"):
"""The spectrum at the Cartesian frequency (xi_x, xi_y), read from the polar grid."""
a = len(spectra)
rho = math.hypot(xi_x, xi_y)
if rho > 1.0 / (2.0 * tau):
return 0j
phi = math.atan2(xi_y, xi_x)
theta, sigma = (phi, rho) if phi >= 0.0 else (phi + math.pi, -rho) # @line L5
if theta >= math.pi:
theta, sigma = 0.0, -sigma
t = theta * a / math.pi
k0 = math.floor(t)
wk = t - k0
if interp == "nearest":
k = int(round(t))
sgn = 1.0
if k == a:
k, sgn = 0, -1.0
r = round(sgn * sigma * length * tau)
return spectra[k][r % length] if -length // 2 <= r < length // 2 else 0j
val = 0j
for k, wt in ((k0, 1.0 - wk), (k0 + 1, wk)):
if wt == 0.0:
continue
sgn = 1.0
if k == a: # angle pi is angle 0 with the radius negated
k, sgn = 0, -1.0
val += wt * _radial(spectra[k], length, sgn * sigma * length * tau) # @line L6
return val
def grid_spectrum(spectra, length, tau, n, pad=2, interp="linear"):
"""The N x N array G (N = pad n) of the Cartesian spectrum, with the pixel-center phase and dxi^2.
G[v mod N][u mod N] = F f(u dxi, v dxi) exp(pi i (u + v) / N) dxi^2 for
u, v = -N/2 .. N/2 - 1, with dxi = 1 / (N h) and the pixel size h = 2 / n.
"""
big = pad * n
dxi = n / (2.0 * big)
g = [[0j] * big for _ in range(big)]
for v in range(-big // 2, big // 2): # @line L4
for u in range(-big // 2, big // 2):
val = polar_value(spectra, length, tau, u * dxi, v * dxi, interp)
g[v % big][u % big] = val * cmath.exp(1j * math.pi * (u + v) / big) * dxi * dxi # @line L7
return g
def spectrum_to_image(g, n):
"""f at the pixel centers from G: f = N^2 IDFT2(G), read at m_x = j - n/2, m_y = n/2 - 1 - i."""
big = len(g)
h = idft2(g) # @line L8
scale = big * big
return [[scale * h[(n // 2 - 1 - i) % big][(j - n // 2) % big].real for j in range(n)] for i in range(n)] # @line L9
def direct_fourier_reconstruction(sino, tau, n, pad=2, over=4, interp="linear"):
"""Reconstruct an n x n image (n even) from a parallel-beam sinogram on [0, pi)."""
if n % 2:
raise ValueError("n must be even")
spectra, length = polar_spectra(sino, tau, over) # @line L1
g = grid_spectrum(spectra, length, tau, n, pad, interp)
return spectrum_to_image(g, 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_direct_fourier_reconstruction.py 123 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/direct-fourier-reconstruction/. The authors are listed in prov/1BAE5C.jsonl.
import cmath
import math
import random
import imgkit as ik
from direct_fourier_reconstruction import (
direct_fourier_reconstruction,
polar_spectra,
polar_value,
spectrum_to_image,
)
A, D, N = 32, 47, 32
TAU = 2.0 * math.sqrt(2.0) / D # the bins cover [-sqrt(2), sqrt(2)], as in imgkit
W = 0.5 # f(x) = exp(-pi |x|^2 / W^2), R f = W exp(-pi s^2 / W^2), F f = W^2 exp(-pi W^2 |xi|^2)
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 gauss_proj(theta, s):
return W * math.exp(-math.pi * s * s / (W * W))
def gauss_ft(rho):
return W * W * math.exp(-math.pi * W * W * rho * rho)
def test_slice_step_matches_analytic_transform() -> None:
# Fourier slice: the scaled DFT of each projection samples F f on its radial line.
for d in (47, 48): # odd and even detectors
tau = 2.0 * math.sqrt(2.0) / d
spectra, length = polar_spectra(sinogram(gauss_proj, 4, d, tau), tau)
for row in spectra:
for l in range(length):
sigma = (l if l < length // 2 else l - length) / (length * tau)
assert abs(row[l] - gauss_ft(sigma)) < 1e-9
def test_grid_to_image_is_exact_on_exact_spectrum() -> None:
big = 2 * N
dxi = N / (2.0 * big)
g = [[0j] * big for _ in range(big)]
for v in range(-big // 2, big // 2):
for u in range(-big // 2, big // 2):
val = gauss_ft(math.hypot(u * dxi, v * dxi))
g[v % big][u % big] = val * cmath.exp(1j * math.pi * (u + v) / big) * dxi * dxi
img = spectrum_to_image(g, N)
xs, ys = ik.pixel_centers(N)
err = max(abs(img[i][j] - math.exp(-math.pi * (xs[j] ** 2 + ys[i] ** 2) / W ** 2)) for i in range(N) for j in range(N))
assert err < 1e-12
def test_polar_value_hermitian_and_close_to_truth() -> None:
spectra, length = polar_spectra(sinogram(gauss_proj), TAU)
rng = random.Random(7)
for _ in range(200):
x, y = rng.uniform(-6, 6), rng.uniform(-6, 6)
p, m = polar_value(spectra, length, TAU, x, y), polar_value(spectra, length, TAU, -x, -y)
assert abs(p - m.conjugate()) < 1e-12
assert abs(p - gauss_ft(math.hypot(x, y))) < 0.01 # bilinear interpolation on the polar grid
assert polar_value(spectra, length, TAU, 10.0, 0.0) == 0 # outside the band 1 / (2 tau)
# the wrap at angle pi: the values just above and just below the negative x axis agree
above = polar_value(spectra, length, TAU, -3.0, 1e-9)
below = polar_value(spectra, length, TAU, -3.0, -1e-9)
assert abs(above - below) < 1e-9
def test_gaussian_known_answer() -> None:
img = direct_fourier_reconstruction(sinogram(gauss_proj), 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 ** 2)) for i in range(N) for j in range(N))
assert err < 0.003 # measured 0.0005 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)
img = direct_fourier_reconstruction(sino, TAU, N)
xs, ys = ik.pixel_centers(N)
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.03 # measured 0.0125
assert max(abs(v) for v in outer) < 0.06 # measured 0.030
def test_shepp_logan_linear_beats_nearest() -> None:
sino = sinogram(lambda th, s: ellipse_projection(ik.SHEPP_LOGAN, th, s))
xs, ys = ik.pixel_centers(N)
inside = [(i, j) for i in range(N) for j in range(N) if xs[j] ** 2 + ys[i] ** 2 < 0.35 ** 2]
errs = {}
for interp in ("linear", "nearest"):
img = direct_fourier_reconstruction(sino, TAU, N, interp=interp)
errs[interp] = max(abs(img[i][j] - ik.ellipse_value(xs[j], ys[i], ik.SHEPP_LOGAN)) for i, j in inside)
if interp == "linear":
assert abs(img[16][16] - 1.02) < 0.05 # measured 1.048
assert errs["linear"] < errs["nearest"] # measured 0.072 and 0.184
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 = (direct_fourier_reconstruction(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 = direct_fourier_reconstruction([[0.0] * 9 for _ in range(4)], 0.3, 6)
assert all(v == 0.0 for row in z for v in row)
History
Bracewell showed in 1956 that the 1D Fourier transform of a strip scan of a radio source is a line of its 2D transform, so that scans at several angles fill the 2D transform. DeRosier and Klug used the same idea in 1968 for 3D structures in electron microscopy, and several groups then applied it to radiography (Kak and Slaney, Section 3.7). Kak and Slaney prefer filtered back-projection, because it can start after the first projection and because linear interpolation is more accurate in space than in the Fourier plane. Stark, Woods, Paul and Hingorani studied this interpolation in 1981 and gave methods that reduce its error. O'Sullivan introduced the gridding method in 1985.
References
- R. N. Bracewell, Strip integration in radio astronomy, Australian Journal of Physics 9, 1956, pp. 198 to 217
- H. Stark, J. W. Woods, I. Paul and R. Hingorani, Direct Fourier reconstruction in computer tomography, IEEE Transactions on Acoustics, Speech, and Signal Processing 29(2), 1981, pp. 237 to 245 (the interpolation from the polar grid to the Cartesian grid)
- J. D. O'Sullivan, A fast sinc function gridding algorithm for Fourier inversion in computer tomography, IEEE Transactions on Medical Imaging 4(4), 1985, pp. 200 to 207
- A. C. Kak and M. Slaney, Principles of Computerized Tomographic Imaging, SIAM Classics in Applied Mathematics 33, 2001, Chapter 3, Section 3.2, equation 22 and Fig. 3.7, pp. 58 to 59 (the method and its interpolation error), Section 3.3.1, p. 62 (the comparison with filtered back-projection), and Section 3.7, p. 110 (the history)
- F. Natterer, The Mathematics of Computerized Tomography, SIAM Classics in Applied Mathematics 32, 2001, Section V.2, Fourier reconstruction
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 1BAE5C Edit this page History Report an error Markdown