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
- Model
- Real RAM
- Properties
- deterministicnot in placenot iterativelineariterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Peter M. Joseph, 1982
Joseph's projector computes an approximate line integral of an image along a ray, for the discrete model 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 on an image, with exactly two weights per row. The error is for smooth images, with 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 on the square , with in row from the top and column from the left. The center of pixel is , , so goes up, and . A ray is the line of the Radon transform. Its direction is . The task is to approximate from the samples , for all rays of a sinogram, and to give the transpose of this map for back projection.
The algorithm
JOSEPH(f, θ, s) ▷ c = cos θ, σ = sin θ, values outside the image are 0- 1
h ← 2/n, p ← 0 - 2
if |c| ≥ |σ| then ▷ the ray is closer to vertical: step along rows - 3
Δ ← h / |c| - 4
for i ← 0 to n - 1 do - 5
x ← (s - y_i σ) / c, u ← ((x + 1) n - 1) / 2 ▷ u = j at the center x_j - 6
j ← ⌊u⌋, t ← u - j - 7
p ← p + Δ ((1 - t) f[i][j] + t f[i][j+1]) - 8
else Δ ← h / |σ| ▷ the ray is closer to horizontal: step along columns - 9
for j ← 0 to n - 1 do y ← (s - x_j c) / σ, v ← ((1 - y) n - 1) / 2, i ← ⌊v⌋, t ← v - i - 10
p ← p + Δ ((1 - t) f[i][j] + t f[i+1][j]) - 11
return p
Line L3 is the length of the ray between two neighboring rows of centers. Along the ray, changes at the rate , so a step of in is a step of along the ray. Line L5 solves the equation of the ray for at the height and turns 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 , so , the centers and . Take , and . Then , the code steps along rows, and . The ray is . Let the image be .
| row | , | weights , | interpolated value | |||
|---|---|---|---|---|---|---|
| 0 | , | , | ||||
| 1 | , | , | ||||
| 2 | , | , | ||||
| 3 | , | , |
The interpolated values add up to , and . The weights in each row add up to , and the eight weights add up to , the length of the ray between and . The test file checks all these values with fractions.Fraction.
The code below also measures accuracy on a grid with 23 bins. For a constant image of value 1, it returns exactly 2 at for every bin with , and exactly at , . For a disk of radius , sampled at the pixel centers, the largest error against over 8 angles and the bins with is , less than one pixel width. For the smooth image , the largest error against is for , for and for . These are measurements of this setup. The error falls by 4 when doubles, as the proof predicts.
Correctness
Joseph's method is an approximation, so correctness here has two parts. First, the code computes the sum , where is the linear interpolant of row with zero values outside the image. Lines L5 and L6 place the crossing point between the two centers and and give its fraction , 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 . The sum over the rows is the midpoint rule for this integral, with error at most when the second partial derivatives of are bounded by . Linear interpolation in each row adds at most per row, or in total. Since , the total error is at most 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 on with , and the center of pixel is with and . The ray is the line with and . Its direction is , and is the arc length along it. We treat the case , which lines L2 to L7 handle. The other case, lines L8 to L10, is the same with the roles of and exchanged. We prove three things: the code computes the quadrature sum that the page defines, the error of that sum is for smooth images, and the back projector is the exact adjoint.
Lemma 1 (the step length, line L3). Between the horizontal lines and , the ray has length .
Proof. Along , , and because and . So a change of in is a change of in .
Lemma 2 (the interpolation, lines L5 to L7). Fix a row . Line L5 finds the point of on the line . Put with and as in line L6, and with for or . Then is the continuous, piecewise linear function of that takes the value at for every integer (with the zero values outside), and line L7 adds .
Proof. gives , which is line L5. The coordinate is an affine function of with exactly at , because . With and , the point lies in and . The linear interpolant of the values at and is . Line L7 skips an index outside the image, which is the same as the value 0 there.
So, with , lines L2 to L7 compute
This is the definition of Joseph's projector on the page. The weight of pixel in it is or , which is what the function ray_weights returns.
Theorem 1 (second order accuracy). Let be twice continuously differentiable on , with outside . Let bound , and . Let . Then for every and
Proof. Write the line integral with as the parameter. The point of at height is with , and by Lemma 1. Put . Since for ,
Split the error in two parts.
Quadrature. The intervals for partition , and is the midpoint rule on them. On one interval of length , the midpoint rule has error at most , so the total error is at most . With , and , so
So .
Interpolation. Fix and put . If , then is the linear interpolant of between two neighbors at distance , and the standard bound for linear interpolation gives . If , then because , and with by continuity, so the error is 0. The case is the same. So .
Add the two parts and divide by : the error is at most . Finally , because and .
The bound is not sharp, but it shows the order: when 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 near the jumps. That is a property of the image model, not of the code.
Theorem 2 (matched back projector). Let be the matrix whose row for ray holds the weights of that ray. The back projector of the code, which adds to pixel for each weight of a ray with value , computes .
Proof. The forward projector computes over the weights of ray . The back projector computes , with the same weights. So for all and , and .
Exact cases. If and , then and in every row, so : the exact integral of the piecewise constant image along the center line of column . If the image is constant, , and the ray meets every row at a point with , then every and , which is the length of the chord of the square between and . The tests check both cases. In the worked example on the page, the samples come from a linear function , and the ray meets every row inside . Linear interpolation and the midpoint rule are both exact for linear functions, so there is the exact integral of along the ray between and .
Complexity
One ray visits rows (or columns) with work each, so it costs time and extra space. A sinogram of angles and bins costs , and the back projection costs the same. The matrix has exactly nonzero entries per row, fewer at the border, so it takes 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 per ray on an 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 (, ) gives exactly times the column sum. A constant image gives exactly 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 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 . Without line L3 the projection of a constant image depends on the angle. Test a constant image at and : the central values must be and .
- Wrong half-pixel offset. The interpolation must use the pixel centers, so at , which needs the 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 , such as the Landweber iteration, can then diverge or converge to a different point.
- Choice of axis. The test must select the axis along which the ray moves slowly. With the opposite choice, can become very large near 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.
# 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
- 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)
- 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.
| 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 YFWYC3 Edit this page History Report an error Markdown