Algorithm Search⌘K

Algorithmadvanced

Joseph's projector

Also called Joseph's method.

Approximate a line integral through an image by linear interpolation between the two nearest pixel centers on each row or column the ray crosses.

Time
O(a d n) worst
Space
O(1) extra
Where
a = the number of projection angles; d = the number of detector bins; n = the side of the n x n image
Properties
deterministicnot in placenot iterativelineariterative
Origin
Peter M. Joseph, 1982

Joseph's projector computes an approximate line integral of an image along a ray, for the discrete model y=Axy = A x of transmission tomography. It treats the image as a set of samples at the pixel centers, not as squares. The ray crosses each row of pixel centers at one point. There the method interpolates linearly between the two nearest samples in the row, and it adds the result times the length of the ray between two rows. If the ray is closer to horizontal, it steps column by column instead. Each ray costs O(n)O(n) on an n×nn \times n image, with exactly two weights per row. The error is O(h2)O(h^2) for smooth images, with h=2/nh = 2/n the pixel size. The weights form a sparse matrix, and the back projector with the same weights is its exact transpose. Compare Siddon's algorithm, which gives the exact lengths of the ray in pixel squares, and the distance-driven projector, which integrates over the width of each detector bin.

In plain words

Think of the image as a grid of measured values, one at the center of each pixel. A ray crosses the image. Pick the direction in which the ray changes slowly: if the ray is closer to vertical, walk down the rows; if it is closer to horizontal, walk across the columns.

At each row, the ray passes between two pixel centers. Estimate the value at the crossing point by a straight-line blend of the two neighbor values: the closer neighbor counts more. Multiply this estimate by the length of the ray between two rows, and add it to the total. When you reach the last row, the total is the projection. Each row gives exactly two weights, so the work is the same for every ray.

The problem

The image is n×nn \times n on the square [−1,1]2[-1, 1]^2, with f[i][j]f[i][j] in row ii from the top and column jj from the left. The center of pixel (i,j)(i, j) is xj=−1+(2j+1)/nx_j = -1 + (2j+1)/n, yi=1−(2i+1)/ny_i = 1 - (2i+1)/n, so yy goes up, and h=2/nh = 2/n. A ray is the line xcos⁡θ+ysin⁡θ=sx\cos\theta + y\sin\theta = s of the Radon transform. Its direction is ω⊥=(−sin⁡θ,cos⁡θ)\omega^\perp = (-\sin\theta, \cos\theta). The task is to approximate Rf(θ,s)=∫f(sω+tω⊥) dt\mathcal{R}f(\theta, s) = \int f(s\omega + t\omega^\perp)\,dt from the samples f[i][j]f[i][j], for all rays of a sinogram, and to give the transpose of this map for back projection.

The algorithm

  1. JOSEPH(f, θ, s) ▷ c = cos θ, σ = sin θ, values outside the image are 0
  2. 1h ← 2/n, p ← 0
  3. 2if |c| ≥ |σ| then ▷ the ray is closer to vertical: step along rows
  4. 3Δ ← h / |c|
  5. 4for i ← 0 to n - 1 do
  6. 5x ← (s - y_i σ) / c, u ← ((x + 1) n - 1) / 2 ▷ u = j at the center x_j
  7. 6j ← ⌊u⌋, t ← u - j
  8. 7p ← p + Δ ((1 - t) f[i][j] + t f[i][j+1])
  9. 8else Δ ← h / |σ| ▷ the ray is closer to horizontal: step along columns
  10. 9for j ← 0 to n - 1 do y ← (s - x_j c) / σ, v ← ((1 - y) n - 1) / 2, i ← ⌊v⌋, t ← v - i
  11. 10p ← p + Δ ((1 - t) f[i][j] + t f[i+1][j])
  12. 11return p

Line L3 is the length of the ray between two neighboring rows of centers. Along the ray, yy changes at the rate cos⁡θ\cos\theta, so a step of hh in yy is a step of h/∣cos⁡θ∣h/|\cos\theta| along the ray. Line L5 solves the equation of the ray for xx at the height yiy_i and turns xx into a fractional column index. Line L7 is linear interpolation in the row. An index outside the image adds nothing. Lines L8 to L10 are the same with rows and columns exchanged.

The pairs (pixel, weight) of lines L7 and L10 are the nonzero entries of one row of the system matrix. The back projector runs the same loops and adds weight times the ray value to each pixel. It is the exact transpose of the forward projector.

Example

Take n=4n = 4, so h=1/2h = 1/2, the centers xj∈{−3/4,−1/4,1/4,3/4}x_j \in \{-3/4, -1/4, 1/4, 3/4\} and yi∈{3/4,1/4,−1/4,−3/4}y_i \in \{3/4, 1/4, -1/4, -3/4\}. Take cos⁡θ=4/5\cos\theta = 4/5, sin⁡θ=3/5\sin\theta = 3/5 and s=0s = 0. Then ∣c∣≥∣σ∣|c| \ge |\sigma|, the code steps along rows, and Δ=(1/2)/(4/5)=5/8\Delta = (1/2)/(4/5) = 5/8. The ray is x=−3y/4x = -3y/4. Let the image be f[i][j]=4i+j+1f[i][j] = 4i + j + 1.

row ii yiy_i xx uu jj, tt weights Δ(1−t)\Delta(1-t), Δt\Delta t interpolated value
0 3/43/4 −9/16-9/16 3/83/8 00, 3/83/8 25/6425/64, 15/6415/64 1+3/8=11/81 + 3/8 = 11/8
1 1/41/4 −3/16-3/16 9/89/8 11, 1/81/8 35/6435/64, 5/645/64 6+1/8=49/86 + 1/8 = 49/8
2 −1/4-1/4 3/163/16 15/815/8 11, 7/87/8 5/645/64, 35/6435/64 10+7/8=87/810 + 7/8 = 87/8
3 −3/4-3/4 9/169/16 21/821/8 22, 5/85/8 15/6415/64, 25/6425/64 15+5/8=125/815 + 5/8 = 125/8

The interpolated values add up to 272/8=34272/8 = 34, and p=(5/8)⋅34=85/4p = (5/8) \cdot 34 = 85/4. The weights in each row add up to Δ=5/8\Delta = 5/8, and the eight weights add up to 5/25/2, the length of the ray between y=−1y = -1 and y=1y = 1. The test file checks all these values with fractions.Fraction.

The code below also measures accuracy on a 32×3232 \times 32 grid with 23 bins. For a constant image of value 1, it returns exactly 2 at θ=0\theta = 0 for every bin with ∣s∣<1−1/n|s| < 1 - 1/n, and exactly 222\sqrt{2} at θ=π/4\theta = \pi/4, s=0s = 0. For a disk of radius 1/21/2, sampled at the pixel centers, the largest error against 21/4−s22\sqrt{1/4 - s^2} over 8 angles and the bins with ∣s∣<0.35|s| < 0.35 is 0.0610.061, less than one pixel width. For the smooth image e−16∣x∣2e^{-16|x|^2}, the largest error against π/16 e−16s2\sqrt{\pi/16}\,e^{-16s^2} is 0.01620.0162 for n=16n = 16, 0.00410.0041 for n=32n = 32 and 0.00100.0010 for n=64n = 64. These are measurements of this setup. The error falls by 4 when nn doubles, as the proof predicts.

Correctness

Joseph's method is an approximation, so correctness here has two parts. First, the code computes the sum Δ∑iϕi(x(yi))\Delta\sum_i \phi_i(x(y_i)), where ϕi\phi_i is the linear interpolant of row ii with zero values outside the image. Lines L5 and L6 place the crossing point between the two centers xjx_j and xj+1x_{j+1} and give its fraction tt, and line L3 is the length of the ray per row. Second, this sum approximates the line integral to second order. Write the line integral as 1∣c∣∫−11f(x(y),y) dy\frac{1}{|c|}\int_{-1}^{1} f(x(y), y)\,dy. The sum over the rows is the midpoint rule for this integral, with error at most h2M/3h^2 M/3 when the second partial derivatives of ff are bounded by MM. Linear interpolation in each row adds at most h2M/8h^2 M/8 per row, or h2M/4h^2 M/4 in total. Since ∣c∣≥1/2|c| \ge 1/\sqrt{2}, the total error is at most (72/12) h2M(7\sqrt{2}/12)\,h^2 M for an image that vanishes near the border. The back projector uses the same weights, so it is the exact transpose. The full proof is in proofs/correctness.md.

Proof: Correctness of Joseph's projectorfull

We use the conventions of the page. The image is n×nn \times n on [−1,1]2[-1, 1]^2 with h=2/nh = 2/n, and the center of pixel (i,j)(i, j) is (xj,yi)(x_j, y_i) with xj=−1+(j+1/2)hx_j = -1 + (j + 1/2)h and yi=1−(i+1/2)hy_i = 1 - (i + 1/2)h. The ray is the line L={(x,y):xc+yσ=s}L = \{(x, y) : x c + y \sigma = s\} with c=cos⁡θc = \cos\theta and σ=sin⁡θ\sigma = \sin\theta. Its direction is ω⊥=(−σ,c)\omega^\perp = (-\sigma, c), and tt is the arc length along it. We treat the case ∣c∣≥∣σ∣|c| \ge |\sigma|, which lines L2 to L7 handle. The other case, lines L8 to L10, is the same with the roles of xx and yy exchanged. We prove three things: the code computes the quadrature sum that the page defines, the error of that sum is O(h2)O(h^2) for smooth images, and the back projector is the exact adjoint.

Lemma 1 (the step length, line L3). Between the horizontal lines y=yiy = y_i and y=yi+1y = y_{i+1}, the ray has length h/∣c∣h/|c|.

Proof. Along LL, dy/dt=cdy/dt = c, and c≠0c \ne 0 because ∣c∣≥∣σ∣|c| \ge |\sigma| and c2+σ2=1c^2 + \sigma^2 = 1. So a change of hh in yy is a change of h/∣c∣h/|c| in tt. □\square

Lemma 2 (the interpolation, lines L5 to L7). Fix a row ii. Line L5 finds the point (x,yi)(x, y_i) of LL on the line y=yiy = y_i. Put ϕi(x)=(1−t)fij+tfi,j+1\phi_i(x) = (1 - t)f_{ij} + t f_{i,j+1} with jj and tt as in line L6, and with fik=0f_{ik} = 0 for k<0k < 0 or k≥nk \ge n. Then ϕi\phi_i is the continuous, piecewise linear function of xx that takes the value fikf_{ik} at xkx_k for every integer kk (with the zero values outside), and line L7 adds Δ ϕi(x)\Delta\,\phi_i(x).

Proof. xc+yiσ=sx c + y_i\sigma = s gives x=(s−yiσ)/cx = (s - y_i\sigma)/c, which is line L5. The coordinate u=((x+1)n−1)/2u = ((x + 1)n - 1)/2 is an affine function of xx with u=ku = k exactly at x=xkx = x_k, because xk+1=(2k+1)/nx_k + 1 = (2k + 1)/n. With j=⌊u⌋j = \lfloor u\rfloor and t=u−j∈[0,1)t = u - j \in [0, 1), the point xx lies in [xj,xj+1)[x_j, x_{j+1}) and t=(x−xj)/ht = (x - x_j)/h. The linear interpolant of the values at xjx_j and xj+1x_{j+1} is (1−t)fij+tfi,j+1(1 - t)f_{ij} + t f_{i,j+1}. Line L7 skips an index outside the image, which is the same as the value 0 there. □\square

So, with Δ=h/∣c∣\Delta = h/|c|, lines L2 to L7 compute

P(θ,s)=Δ∑i=0n−1ϕi ⁣(s−yiσc).P(\theta, s) = \Delta \sum_{i=0}^{n-1} \phi_i\!\left(\frac{s - y_i\sigma}{c}\right).

This is the definition of Joseph's projector on the page. The weight of pixel (i,j)(i, j) in it is Δ(1−t)\Delta(1 - t) or Δt\Delta t, which is what the function ray_weights returns.

Theorem 1 (second order accuracy). Let ff be twice continuously differentiable on R2\mathbb{R}^2, with f=0f = 0 outside [−1+h/2,1−h/2]2[-1 + h/2, 1 - h/2]^2. Let MM bound ∣fxx∣|f_{xx}|, ∣fxy∣|f_{xy}| and ∣fyy∣|f_{yy}|. Let fij=f(xj,yi)f_{ij} = f(x_j, y_i). Then for every θ\theta and ss

∣P(θ,s)−Rf(θ,s)∣≤7h2M12 ∣c∣≤7212 h2M.|P(\theta, s) - \mathcal{R}f(\theta, s)| \le \frac{7 h^2 M}{12\,|c|} \le \frac{7\sqrt{2}}{12}\, h^2 M.

Proof. Write the line integral with yy as the parameter. The point of LL at height yy is (X(y),y)(X(y), y) with X(y)=(s−yσ)/cX(y) = (s - y\sigma)/c, and dt=dy/∣c∣dt = dy/|c| by Lemma 1. Put g(y)=f(X(y),y)g(y) = f(X(y), y). Since f=0f = 0 for ∣y∣>1|y| > 1,

Rf(θ,s)=1∣c∣∫−11g(y) dy.\mathcal{R}f(\theta, s) = \frac{1}{|c|}\int_{-1}^{1} g(y)\,dy.

Split the error in two parts.

Quadrature. The intervals [yi−h/2,yi+h/2][y_i - h/2, y_i + h/2] for i=0,…,n−1i = 0, \ldots, n-1 partition [−1,1][-1, 1], and h∑ig(yi)h\sum_i g(y_i) is the midpoint rule on them. On one interval of length hh, the midpoint rule has error at most h3max⁡∣g′′∣/24h^3 \max|g''|/24, so the total error is at most nh3max⁡∣g′′∣/24=h2max⁡∣g′′∣/12n h^3 \max|g''|/24 = h^2\max|g''|/12. With τ=σ/c\tau = \sigma/c, X′(y)=−τX'(y) = -\tau and ∣τ∣≤1|\tau| \le 1, so

g′′=τ2fxx−2τfxy+fyy,∣g′′∣≤4M.g'' = \tau^2 f_{xx} - 2\tau f_{xy} + f_{yy}, \qquad |g''| \le 4M.

So ∣∫−11g dy−h∑ig(yi)∣≤h2M/3\left|\int_{-1}^{1} g\,dy - h\sum_i g(y_i)\right| \le h^2 M/3.

Interpolation. Fix ii and put x=X(yi)x = X(y_i). If x0≤x≤xn−1x_0 \le x \le x_{n-1}, then ϕi(x)\phi_i(x) is the linear interpolant of f(⋅,yi)f(\cdot, y_i) between two neighbors at distance hh, and the standard bound for linear interpolation gives ∣ϕi(x)−f(x,yi)∣≤h2M/8|\phi_i(x) - f(x, y_i)| \le h^2 M/8. If x<x0x < x_0, then f(x,yi)=0f(x, y_i) = 0 because x<−1+h/2x < -1 + h/2, and ϕi(x)=tfi0\phi_i(x) = t f_{i0} with fi0=f(−1+h/2,yi)=0f_{i0} = f(-1 + h/2, y_i) = 0 by continuity, so the error is 0. The case x>xn−1x > x_{n-1} is the same. So ∣h∑iϕi(X(yi))−h∑ig(yi)∣≤nh⋅h2M/8=h2M/4\left|h\sum_i \phi_i(X(y_i)) - h\sum_i g(y_i)\right| \le n h \cdot h^2 M/8 = h^2 M/4.

Add the two parts and divide by ∣c∣|c|: the error is at most (1/3+1/4)h2M/∣c∣=7h2M/(12∣c∣)(1/3 + 1/4)h^2 M/|c| = 7h^2M/(12|c|). Finally ∣c∣≥1/2|c| \ge 1/\sqrt{2}, because ∣c∣≥∣σ∣|c| \ge |\sigma| and c2+σ2=1c^2 + \sigma^2 = 1. □\square

The bound is not sharp, but it shows the order: when nn doubles, the error falls by about 4. The page gives the measured values for a Gaussian. For a piecewise constant image, such as a disk, the samples jump, and the error is of the order of hh near the jumps. That is a property of the image model, not of the code.

Theorem 2 (matched back projector). Let AA be the matrix whose row for ray (θ,s)(\theta, s) holds the weights of that ray. The back projector of the code, which adds w vw\,v to pixel (i,j)(i, j) for each weight ww of a ray with value vv, computes ATvA^T v.

Proof. The forward projector computes (Ax)r=∑(i,j,w)w xij(Ax)_r = \sum_{(i,j,w)} w\,x_{ij} over the weights of ray rr. The back projector computes (Bv)ij=∑r∑(i,j,w) of rw vr(Bv)_{ij} = \sum_r \sum_{(i,j,w) \text{ of } r} w\,v_r, with the same weights. So ⟨Ax,v⟩=∑r∑(i,j,w)w xij vr=⟨x,Bv⟩\langle Ax, v\rangle = \sum_r\sum_{(i,j,w)} w\,x_{ij}\,v_r = \langle x, Bv\rangle for all xx and vv, and B=ATB = A^T. □\square

Exact cases. If θ=0\theta = 0 and s=xjs = x_j, then u=ju = j and t=0t = 0 in every row, so P=h∑ifijP = h\sum_i f_{ij}: the exact integral of the piecewise constant image along the center line of column jj. If the image is constant, fij=1f_{ij} = 1, and the ray meets every row at a point xx with x0≤x≤xn−1x_0 \le x \le x_{n-1}, then every ϕi=1\phi_i = 1 and P=nh/∣c∣=2/∣c∣P = nh/|c| = 2/|c|, which is the length of the chord of the square between y=−1y = -1 and y=1y = 1. The tests check both cases. In the worked example on the page, the samples come from a linear function FF, and the ray meets every row inside [x0,xn−1][x_0, x_{n-1}]. Linear interpolation and the midpoint rule are both exact for linear functions, so there PP is the exact integral of FF along the ray between y=−1y = -1 and y=1y = 1.

Complexity

One ray visits nn rows (or columns) with O(1)O(1) work each, so it costs O(n)O(n) time and O(1)O(1) extra space. A sinogram of aa angles and dd bins costs O(adn)O(a d n), and the back projection costs the same. The matrix has exactly 2n2n nonzero entries per row, fewer at the border, so it takes O(adn)O(a d n) memory if it is stored. The cost per ray does not depend on the angle or the offset, which makes the loops easy to vectorize. On a GPU, line L7 is one hardware texture fetch with linear filtering. In 3D, the method steps through the slices along the main direction and interpolates bilinearly in each slice, at O(n)O(n) per ray on an n×n×nn \times n \times n volume.

Properties

  • Linear and matched. The projection is a linear map of the image, and the back projector with the same weights is its exact adjoint.
  • Smooth image model. The method integrates the row-wise linear interpolant of the samples, not the pixel squares. For smooth images it is second order accurate. For an image with jumps, such as a disk, the error near a jump is of the order of one pixel, as for any discrete model.
  • Exact on the grid. A ray through the centers of one column (θ=0\theta = 0, s=xjs = x_j) gives exactly hh times the column sum. A constant image gives exactly 2/∣cos⁡θ∣2/|\cos\theta| for the rays that meet every row inside the outer centers.
  • Direction dependent model. The interpolation runs along rows for some angles and along columns for others. At θ=π/4\theta = \pi/4 the method switches from one model to the other, so the weights of a ray change abruptly there. For a smooth image both models are second order, and the jump in the projection is small.
  • Ray-driven. Like Siddon's algorithm, it samples the image along a ray of zero width. When the detector bins are wider than the pixels, the back projection of a smooth sinogram can show a moire pattern of high frequency.

Variants and improvements

  • 3D and cone beam. Step through the slices perpendicular to the main axis of the ray and interpolate bilinearly in each slice. This is the common form in cone-beam iterative reconstruction.
  • Hardware interpolation. On GPUs, the interpolation of line L7 or its 3D form uses the texture units. The forward projector is then very fast, but the back projector needs a separate kernel, and the two are often not exact transposes. Many codes accept this unmatched pair.
  • Siddon's algorithm. The exact intersection lengths model the image as pixel squares. They give a different matrix with a varying number of entries per row.
  • Distance-driven projection. The distance-driven projector maps the pixel borders and the bin borders onto one axis and uses their overlaps. It has no moire pattern in the back projection.
  • Pixel-driven projection. The pixel-driven projector loops over pixels and splits each one between the two nearest bins. It is the natural back projector of filtered back-projection, but as a forward projector it has a ripple in the projections.

When to use it

Use Joseph's projector as the forward and back projector of an iterative method such as SART or SIRT when the image is smooth on the scale of a pixel and the detector bins are about as wide as a pixel. It costs the same for every ray, it vectorizes well, and it gives a smaller error than the pixel-square model on smooth images. Use Siddon's algorithm when the model must be the exact path length in pixel squares, for example for dose calculation. Use the distance-driven projector when the bins are much wider than the pixels or when the back projection must be free of artifacts.

Pitfalls

  • Forgetting the factor 1/∣cos⁡θ∣1/|\cos\theta|. Without line L3 the projection of a constant image depends on the angle. Test a constant image at θ=0\theta = 0 and θ=π/4\theta = \pi/4: the central values must be 22 and 222\sqrt{2}.
  • Wrong half-pixel offset. The interpolation must use the pixel centers, so u=ju = j at x=xjx = x_j, which needs the −1-1 in line L5. An index measured from the pixel edge shifts the whole projection by half a pixel.
  • The border. Near the edge of the image, one of the two neighbors is outside. It must count as zero, not be clamped to the edge value, or the projection of an image with nonzero border values grows outside the image.
  • Unmatched back projector. A back projector that interpolates in the sinogram (pixel-driven) is not the transpose of Joseph's forward projector. An iterative method that assumes ATA^T, such as the Landweber iteration, can then diverge or converge to a different point.
  • Choice of axis. The test ∣cos⁡θ∣≥∣sin⁡θ∣|\cos\theta| \ge |\sin\theta| must select the axis along which the ray moves slowly. With the opposite choice, Δ\Delta can become very large near θ=π/2\theta = \pi/2 and the interpolation steps over many pixels.

Implementations

The Python code computes the weights of one ray with float or fractions.Fraction input, the forward projector, the back projector and the sparse matrix, with the bins of the shared pixel-driven projector. The tests check the worked example exactly, axis-aligned rays, the adjoint, the matrix, a constant image, a disk, and the second order error on a Gaussian.

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.

imgkit.pyI0RawGitHub
# 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
joseph_projector.py 100 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/joseph-projector/. The authors are listed in prov/YFWYC3.jsonl.
"""Joseph's projector: line integrals through an image by linear interpolation along rows or columns.

Conventions:
- The image is n x n on the square [-1, 1]^2, stored as img[i][j] with row i
  from the top and column j from the left. 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.
- A ray is the line x cos(theta) + y sin(theta) = s.
- The code works with float or with fractions.Fraction values of
  cos(theta), sin(theta) and s. With Fraction input the result is exact.
"""

import math
from fractions import Fraction


def ray_weights(n, c, sn, s):
    """The (i, j, weight) entries of the ray x c + y sn = s, with c = cos(theta) and sn = sin(theta).

    The weights are the linear interpolation weights in each row (or column)
    times the length of the ray between two rows (or columns). An index
    outside the image gets no weight, which is the same as a zero value there.
    """
    exact = any(isinstance(v, Fraction) for v in (c, sn, s))
    h = Fraction(2, n) if exact else 2.0 / n  # @line L1
    out = []
    if abs(c) >= abs(sn):  # @line L2
        step = h / abs(c)  # @line L3
        for i in range(n):  # @line L4
            y = 1 - (2 * i + 1) * h / 2
            x = (s - y * sn) / c  # @line L5
            u = ((x + 1) * n - 1) / 2  # the column coordinate: u = j at the center x_j
            j = math.floor(u)  # @line L6
            t = u - j
            for jj, w in ((j, 1 - t), (j + 1, t)):  # @line L7
                if 0 <= jj < n and w != 0:
                    out.append((i, jj, step * w))
    else:
        step = h / abs(sn)  # @line L8
        for j in range(n):
            x = -1 + (2 * j + 1) * h / 2
            y = (s - x * c) / sn  # @line L9
            v = ((1 - y) * n - 1) / 2  # the row coordinate: v = i at the center y_i
            i = math.floor(v)
            t = v - i
            for ii, w in ((i, 1 - t), (i + 1, t)):  # @line L10
                if 0 <= ii < n and w != 0:
                    out.append((ii, j, step * w))
    return out


def joseph_ray(img, c, sn, s):
    """The line integral of the interpolated image along x c + y sn = s."""
    return sum(w * img[i][j] for i, j, w in ray_weights(len(img), c, sn, s))  # @line L11


def bin_centers(nbins):
    """s_b = -sqrt(2) + (b + 1/2) w with w = 2 sqrt(2) / nbins, the bins of imgkit."""
    smax = math.sqrt(2.0)
    width = 2.0 * smax / nbins
    return [-smax + (b + 0.5) * width for b in range(nbins)]


def joseph_project(img, angles, nbins):
    """The sinogram as a flat list: entry k * nbins + b holds angle k and bin b."""
    out = []
    for theta in angles:
        c, sn = math.cos(theta), math.sin(theta)
        out.extend(joseph_ray(img, c, sn, s) for s in bin_centers(nbins))
    return out


def joseph_back_project(n, angles, nbins, values):
    """The adjoint of joseph_project: each ray adds its value times its weights to its pixels."""
    out = [[0.0] * n for _ in range(n)]
    k = 0
    for theta in angles:
        c, sn = math.cos(theta), math.sin(theta)
        for s in bin_centers(nbins):
            v = values[k]
            k += 1
            if v == 0:
                continue
            for i, j, w in ray_weights(n, c, sn, s):
                out[i][j] += w * v
    return out


def joseph_matrix(n, angles, nbins):
    """The system matrix as sparse rows of (column, weight) pairs, column i * n + j."""
    rows = []
    for theta in angles:
        c, sn = math.cos(theta), math.sin(theta)
        for s in bin_centers(nbins):
            acc = {}
            for i, j, w in ray_weights(n, c, sn, s):
                acc[i * n + j] = acc.get(i * n + j, 0.0) + w
            rows.append(sorted(acc.items()))
    return rows
test_joseph_projector.py 105 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/joseph-projector/. The authors are listed in prov/YFWYC3.jsonl.

import math
import random
from fractions import Fraction as F

import imgkit as ik
from joseph_projector import (
    bin_centers,
    joseph_back_project,
    joseph_matrix,
    joseph_project,
    joseph_ray,
    ray_weights,
)


def test_worked_example() -> None:
    # n = 4, cos = 4/5, sin = 3/5, s = 0: x = -3 y / 4 in each row
    w = ray_weights(4, F(4, 5), F(3, 5), F(0))
    assert w == [
        (0, 0, F(25, 64)), (0, 1, F(15, 64)),
        (1, 1, F(35, 64)), (1, 2, F(5, 64)),
        (2, 1, F(5, 64)), (2, 2, F(35, 64)),
        (3, 2, F(15, 64)), (3, 3, F(25, 64)),
    ]
    img = [[4 * i + j + 1 for j in range(4)] for i in range(4)]
    assert joseph_ray(img, F(4, 5), F(3, 5), F(0)) == F(85, 4)


def test_axis_aligned_rays() -> None:
    rng = random.Random(1)
    n = 8
    img = [[F(rng.randint(-9, 9)) for _ in range(n)] for _ in range(n)]
    h = F(2, n)
    for j in range(n):
        x = -1 + (2 * j + 1) * h / 2
        assert joseph_ray(img, F(1), F(0), x) == h * sum(img[i][j] for i in range(n))
    for i in range(n):
        y = 1 - (2 * i + 1) * h / 2
        assert joseph_ray(img, F(0), F(1), y) == h * sum(img[i])


def test_adjoint() -> None:
    rng = random.Random(2)
    n, nbins = 16, 23
    angles = [k * math.pi / 7 for k in range(7)]
    x = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(n)]
    y = [rng.uniform(-1, 1) for _ in range(len(angles) * nbins)]
    ax = joseph_project(x, angles, nbins)
    aty = joseph_back_project(n, angles, nbins, y)
    lhs = sum(a * b for a, b in zip(ax, y))
    rhs = ik.img_dot(x, aty)
    assert abs(lhs - rhs) <= 1e-10 * math.sqrt(sum(a * a for a in ax)) * math.sqrt(sum(b * b for b in y))


def test_matrix_matches_projector() -> None:
    rng = random.Random(3)
    n, nbins = 16, 23
    angles = [0.0, 0.5, 1.0, 2.0]
    x = [[rng.random() for _ in range(n)] for _ in range(n)]
    a = ik.sp_matvec(joseph_matrix(n, angles, nbins), ik.flatten(x))
    b = joseph_project(x, angles, nbins)
    assert max(abs(p - q) for p, q in zip(a, b)) < 1e-12


def test_constant_image() -> None:
    n, nbins = 32, 23
    one = [[1.0] * n for _ in range(n)]
    p = joseph_project(one, [0.0, math.pi / 4], nbins)
    for b, s in enumerate(bin_centers(nbins)):
        if abs(s) < 1 - 1 / n:
            assert abs(p[b] - 2.0) < 1e-12
    assert abs(p[nbins + nbins // 2] - 2.0 * math.sqrt(2.0)) < 1e-12


def test_disk_projection() -> None:
    n, nbins = 32, 23
    angles = [k * math.pi / 8 for k in range(8)]
    img = ik.disk_phantom(n, 0.5)
    p = joseph_project(img, angles, nbins)
    q = ik.sp_matvec(ik.parallel_beam_matrix(n, angles, nbins), ik.flatten(img))
    for k in range(len(angles)):
        for b, s in enumerate(bin_centers(nbins)):
            if abs(s) < 0.35:
                exact = 2.0 * math.sqrt(0.25 - s * s)
                assert abs(p[k * nbins + b] - exact) < 2.0 / n
                assert abs(p[k * nbins + b] - q[k * nbins + b]) < 0.1


def test_gaussian_second_order() -> None:
    errs = []
    nbins = 23
    for n in (16, 32):
        xs, ys = ik.pixel_centers(n)
        g = [[math.exp(-16.0 * (x * x + y * y)) for x in xs] for y in ys]
        p = joseph_project(g, [0.3, 1.1], nbins)
        e = 0.0
        for k in range(2):
            for b, s in enumerate(bin_centers(nbins)):
                e = max(e, abs(p[k * nbins + b] - math.sqrt(math.pi / 16.0) * math.exp(-16.0 * s * s)))
        errs.append(e)
    assert errs[1] < 0.005
    assert errs[0] / errs[1] > 3.0

History

Peter M. Joseph published the method in IEEE Transactions on Medical Imaging in 1982, in the first volume of the journal, as an improved way to reproject rays through pixel images. Its fixed cost per ray and its smooth image model made it a standard forward projector in iterative CT reconstruction. In 2002 and 2004, De Man and Basu compared ray-driven and pixel-driven projectors with their distance-driven projector, which removes the artifacts that thin rays give in the back projection.

References

  1. Peter M. Joseph, An improved algorithm for reprojecting rays through pixel images, IEEE Transactions on Medical Imaging 1(3), 1982, pp. 192 to 196 (the method as a whole; section numbers not confirmed)
  2. Bruno De Man and Samit Basu, Distance-driven projection and backprojection in three dimensions, Physics in Medicine and Biology 49(11), 2004, pp. 2463 to 2475 (the comparison of pixel-driven, ray-driven and distance-driven projectors; general locator)

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