Algorithmadvanced
Distance-driven projector
Also called distance-driven projection.
A matched forward and back projector for CT that maps pixel borders and detector bin borders onto one axis and uses the lengths of their overlaps as weights.
- Time
- O(a n (n + d)) worst
- Space
- O(n + d) 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
- Bruno De Man, Samit Basu, 2002
The distance-driven projector computes the system matrix of the discrete model of transmission tomography, where holds the pixel values and the detector readings of a sinogram. For one view it takes each row of pixels (or each column, for a ray closer to horizontal), maps the borders of the pixels in that row and the borders of the detector bins onto one common axis, and uses the length of the overlap of each pixel and each bin as the weight. The back projector uses the same weights, so it is the exact transpose. One view costs for an image and bins. De Man and Basu designed it to remove the two known faults of the simpler projectors: the pixel-driven projector gives a high frequency ripple in the forward projection, and ray-driven projectors such as Siddon's algorithm and Joseph's projector give a similar artifact in the back projection when the bins are wide.
In plain words
Look at one row of pixels from the direction of the rays. Each pixel casts a shadow on the detector line. The shadows of the pixels in one row lie side by side, with no gap and no overlap. The detector is cut into bins, also side by side. Put the two cuttings on the same line, like two rulers next to each other. Where the shadow of a pixel and a bin overlap, the pixel sends that share of itself to that bin.
The bin value is then the average over the bin of what the rays see. Because both sets of cells cover the line with no gap, each pixel gives all of its mass to the bins, and a constant image gives a flat projection with no ripple. The back projection runs the same overlaps in the other direction.
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 is the pixel size. A view has the angle , with , and the detector coordinate of a point is , as for the Radon transform. Bin covers for . The code uses the bins of the shared pixel-driven projector: bins of width on .
The image model is this. Suppose . Then each row of pixels is collapsed onto its center line , with the thickness . A ray crosses the row along a path of length , and it sees the value of the pixel where it meets the center line. The bin value is the average over the bin width of the sum of these row contributions. For , swap the roles of rows and columns, with . The task is to compute all bin values of all views, and the transpose of this linear map.
The algorithm
DD-VIEW(f, c, σ, s0, w, d) ▷ c = cos θ, σ = sin θ; out has d zeros- 1
h ← 2/n - 2
if |c| ≥ |σ| then Δ ← h/|c|, the lines are rows else Δ ← h/|σ|, the lines are columns - 3
for k ← 0 to n - 1 do ▷ row k, or column k - 4
B ← the n + 1 pixel borders of line k mapped to s = x c + y σ, in increasing order - 5
D ← the bin borders s0, s0 + w, ..., s0 + d w - 6
p ← 0, q ← 0 ▷ p: a pixel of line k, q: a bin - 7
while p < n and q < d do - 8
ℓ ← min(B[p+1], D[q+1]) - max(B[p], D[q]) - 9
if ℓ > 0 then out[q] ← out[q] + (Δ ℓ / w) · f[pixel p of line k] - 10
if B[p+1] < D[q+1] then p ← p + 1 else q ← q + 1 - 11
return out
For a row the borders are at the height , so holds for . These values are equally spaced, apart. If they decrease, and line L4 reverses them, which also reverses the order of the pixels. Lines L6 to L10 are the merge of two sorted lists, as in merge sort: at each step the cell that ends first moves on. Line L8 is the overlap of pixel and bin , and line L9 adds the share of the pixel. The factor makes the weights of one pixel, times , sum to , the pixel area, when the detector covers its shadow.
The pairs (pixel, bin, weight) of line L9 are the nonzero entries of one view of the system matrix. The back projector runs the same loops and adds weight times the bin value to the pixel. It is the exact transpose.
Example
Take , so , the image , , and four bins of width on . Then , the lines are rows, and .
| row | borders | pixel and its shadow | overlaps with the bins | weights | |
|---|---|---|---|---|---|
| 0 | : | bin 1: , bin 2: | , | ||
| : | bin 2: , bin 3: | , | |||
| 1 | : | bin 0: , bin 1: | , | ||
| : | bin 1: , bin 2: | , |
The bin values are . The shadow of a pixel has the width . The detector ends at , so it misses , that is , of the shadow of pixel and of the shadow of pixel . So times the sum of the bins is , the image mass minus the missed parts. The test file checks every weight, every bin value and this sum with fractions.Fraction.
The code also measures the projector on a grid with bins. For a constant image of value 1, every bin that lies fully inside the part of the detector where each ray crosses all rows gets exactly , within , at the angles , , and . The pixel-driven projector of the shared helper differs from the same value by up to percent on the same bins: that is its ripple. For a disk of radius sampled at the pixel centers, over 8 angles and the bins with , the largest difference from the bin average of is . For the image sampled at the pixel centers, the largest difference from the bin average of is for , for and for . These are measurements of this setup with the bin width fixed at .
Correctness
The proof has three parts, and the full form is in proofs/correctness.md. First, the sweep of lines L6 to L10 visits every pair of a pixel and a bin whose intervals overlap with positive length, once each. Both lists are sorted and each is a partition of an interval. The loop keeps the invariant that all pairs with or that overlap have been visited, because a cell is dropped only when it ends before the other current cell, and then it cannot meet any later cell of the other list. Second, the weight of a pair is , which is the integral over the bin, divided by , of the row contribution for the rays that meet the center line inside the pixel. So the code computes the model of "The problem" exactly. Third, the back projector uses the same list of weights, so it is the transpose.
Two exact facts follow. If the detector covers the shadow of the whole image, , the integral of the pixel-square image. At , the rays are vertical and the collapse of a row onto its center line changes nothing, so each bin gets the exact average over its width of the line integrals of the pixel-square image.
The method is still an approximation of the X-ray transform of the pixel-square image at other angles, because it collapses each row to its center line. A ray that crosses a pixel near its corner sees the full of that pixel, while its true path through the square is shorter.
Proof: Correctness of the distance-driven projectorfull
We use the conventions of the page. The image is on with , the view has and , and bin is for . We treat the case , where the lines are rows and . The column case is the same with and exchanged. We work in exact arithmetic.
The model. For row , let be the value of the pixel of row whose part of the center line the ray meets, and if it meets none. The model value of bin is
We prove that DD-VIEW returns for all , that the back projector is the transpose, and the two exact facts of the page.
Lemma 1 (the borders, line L4). On the center line of row , pixel is the segment . The ray with parameter meets it if and only if lies between and .
Proof. On the line , the map is affine with slope (since and , ). So it maps the segment of the pixel onto the interval between the images of its ends, one to one.
So the shadows of the pixels of row are the intervals between neighbors of the list , each of length , and they tile the interval . If , the list decreases in ; line L4 reverses it, and pixel of the sorted list is column . Lines L4 and L5 give two increasing lists. Call the cells and .
Lemma 2 (the sweep, lines L6 to L10). The loop visits every pair with exactly once, and line L8 sets for it.
Proof. For two closed intervals, of the right ends minus of the left ends is the length of the intersection when it is positive, and it is when they overlap in at most one point. So line L8 is correct, and line L9 adds a term only for pairs with positive overlap.
Each step increases or by one, so no pair is visited twice, and the loop ends after at most steps. Invariant: when the loop is at , every pair with positive overlap and with or was visited. It holds at . Suppose the loop moves from to , because . The pairs that the move gives up are with . For those, starts at , so ends before begins and the overlap is zero. The move to with is the same with the roles exchanged: with starts at , so it meets in at most one point. When the loop stops, or . If , every pair with a positive overlap has and was visited. If , the same holds for the bins.
Theorem (the forward projector). DD-VIEW returns .
Proof. By Lemma 1, for in the interior of , where is the column of sorted pixel , and outside . The ends of the intervals are a finite set and do not change the integral. So
By Lemma 2, line L9 adds exactly the terms of this sum with positive overlap, for each row that line L3 visits. Summing over gives .
Theorem (the transpose). Let be the list of triples that line L9 uses for all views. The forward projector is , and the back projector of the code is . Then for all and , so the back projector is . A pixel and a bin may appear in two triples only if they come from two views, which are different rows of , so the sum over is the sum over the nonzero entries of .
Corollary 1 (mass). If and for a view, then .
Proof. Under the hypothesis, the bins tile an interval that contains each . So . Then .
Corollary 2 (a constant image). Let and let bin lie inside every interval , . Then .
Proof. For each row, the tile an interval that contains , so , and the row adds .
The intervals of the rows are , and . So the condition of Corollary 2 holds for every bin with , which is the condition that the test uses.
Corollary 3 (axis-aligned rays). At , is the average over of the exact line integral of the pixel-square image .
Proof. At the ray is the vertical line . For inside column , it crosses every row in a segment of length inside pixel , so the line integral is . Integrate over and divide by .
Remark (the approximation). For other angles the model differs from the line integral of the pixel-square image. The ray crosses row along a segment of length , which may pass through two pixels of the row, while the model gives the whole length to the pixel at the center line. For one row, the difference is at most times the jump of between the two neighbors, and it occurs only for the rays whose segment in the row crosses a pixel border. For an image with a bounded gradient the jump is , so the difference per row is and the sum over the rows is . This is a property of the model, not of the code.
Cost. By Lemma 2 the sweep of one line takes at most steps of work, and lines L4 and L5 take . With lines per view and views, the time is in the real-RAM model, and the extra space is that of the two lists, .
Complexity
In the real-RAM model:
- Lines L4 and L5 build two sorted lists of and numbers in time.
- The loop of lines L7 to L10 moves or at each step, so it runs at most times with work each.
- Line L3 repeats this for lines.
So one view costs time and extra space, and a sinogram of views costs . In practice is about , which gives , the same order as the pixel-driven and the ray-driven projectors, which cost and . The number of nonzero weights per view is at most , because each step of the sweep gives at most one. A real code computes the bin borders once per view, not once per line. In 3D, De Man and Basu map the voxel borders and the detector cell borders onto a common plane and take the overlaps in the two directions separately, as the product of two 1D overlaps.
Properties
- Matched pair. The back projector is the exact transpose of the forward projector. The test checks .
- No ripple. A constant image gives a flat projection inside the image, because the shadows of the pixels in a row tile the detector line with no gap and no overlap. The pixel-driven projector splits each pixel between the two nearest bin centers, so its projection of a constant image ripples.
- No moire pattern in the back projection. Each bin spreads its value over all pixels whose shadows it overlaps, in proportion to the overlap. A ray-driven back projector with thin rays misses pixels when the bins are wider than the pixels.
- Mass conservation. Each pixel sends exactly its area, times its value, to the detector.
- Direction dependent model. The lines switch from rows to columns at . At both models apply, and they give slightly different weights.
- Positive weights. All weights are nonnegative, which the convergence results of SART and SIRT need for their row and column sums.
Variants and improvements
- Three dimensions (De Man and Basu 2004). Map the voxel borders and the detector cell borders onto a plane through the center of the volume, and take the area of overlap as the product of the overlaps in the two directions. The cost per view stays proportional to the number of voxels plus the number of detector cells per line.
- Fan beam and cone beam. The rays of a view meet in a source point. The borders are mapped by a central projection from the source onto the common axis, not by the parallel map of line L4. The overlaps and the sweep are the same.
- Branchless distance-driven projection. For GPUs, later work replaces the sweep with a difference of integrals of the image: precompute the cumulative sums of each line, then each bin value is a difference of two interpolated cumulative sums. This removes the branch of line L10.
- Separable footprints. Long, Fessler and Balter in 2010 model the footprint of a voxel on the detector as a trapezoid instead of a rectangle. This is more accurate at oblique angles, at a higher cost.
When to use it
Use the distance-driven projector as the forward and back projector of an iterative method, such as SART, SIRT, MLEM or penalized least squares, when the detector bins are about as wide as the pixels or wider, and when the back projection must be free of high frequency artifacts. Use Siddon's algorithm when the weights must be the exact path lengths, and Joseph's projector for a smooth image model with a fixed cost per ray. Filtered back-projection needs only a back projector, and the pixel-driven back projector with linear interpolation is the usual choice there.
Pitfalls
- Decreasing borders. For (rows) or for the column case, the mapped borders come out in decreasing order. The merge needs increasing lists, so line L4 must reverse them and also reverse the pixel index.
- Wrong normalization of the back projector. Some codes divide the back projected overlaps by the pixel width instead of the bin width, so that a constant sinogram gives a flat image. That pair is not an exact transpose. Use the same weights in both directions when an iterative method assumes .
- Detector too short. If the bins do not cover the shadow of the image, mass leaks out at the ends, as in the example. This is correct for the model, but a test of mass conservation must use a detector that covers the image.
- Equal borders. If a pixel border and a bin border coincide, line L8 gives for one pair. Line L9 must skip it, or the matrix gets explicit zero entries.
- Forgetting the factor . Without the projection of a constant image depends on the angle.
Implementations
The Python code computes the weights of one view 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 imgkit.parallel_beam_matrix. The tests check the worked example exactly, the exact mass conservation for random integer images at five rational angles, the flat projection of a constant image against the ripple of the pixel-driven projector, the adjoint, the matrix against the projector, and the projection of a disk against the analytic Radon transform averaged over each bin.
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/distance-driven-projector/. The authors are listed in prov/MVREDC.jsonl.
"""The distance-driven projector and its exact transpose, for 2D parallel beams.
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 view has the angle theta, and the detector coordinate of a point (x, y)
is s = x cos(theta) + y sin(theta). Bin b covers [s0 + b w, s0 + (b + 1) w].
- The value of a bin is the average over its width of the projection of the
image model: inside each row (or column) the image is constant on each
pixel, and the row has the thickness h / |cos(theta)| along the ray.
- The code works with float or with fractions.Fraction values of cos(theta),
sin(theta), s0 and w. With Fraction input the weights are exact.
"""
import math
from fractions import Fraction
def _overlaps(pb, bb):
"""Sweep two increasing lists of cell borders; yield (cell of pb, cell of bb, overlap length)."""
p, q = 0, 0
while p < len(pb) - 1 and q < len(bb) - 1: # @line L7
length = min(pb[p + 1], bb[q + 1]) - max(pb[p], bb[q]) # @line L8
if length > 0:
yield p, q, length # @line L9
if pb[p + 1] < bb[q + 1]: # @line L10
p += 1
else:
q += 1
def view_weights(n, c, sn, s0, w, nbins):
"""The (b, i, j, weight) entries of one view with c = cos(theta), sn = sin(theta)."""
exact = any(isinstance(v, Fraction) for v in (c, sn, s0, w))
h = Fraction(2, n) if exact else 2.0 / n # @line L1
bins = [s0 + b * w for b in range(nbins + 1)] # @line L5
out = []
rows = abs(c) >= abs(sn) # @line L2
step = h / abs(c) if rows else h / abs(sn)
for k in range(n): # @line L3
if rows: # row k: pixel borders x = -1 + j h at the height y_k
y = 1 - (2 * k + 1) * h / 2
borders = [(-1 + j * h) * c + y * sn for j in range(n + 1)]
else: # column k: pixel borders y = 1 - i h at the abscissa x_k
x = -1 + (2 * k + 1) * h / 2
borders = [x * c + (1 - i * h) * sn for i in range(n + 1)]
flip = borders[0] > borders[-1] # @line L4
if flip:
borders.reverse()
for p, b, length in _overlaps(borders, bins): # @line L6
m = n - 1 - p if flip else p
i, j = (k, m) if rows else (m, k)
out.append((b, i, j, step * length / w))
return out
def detector(nbins):
"""(s0, w) of the bins of imgkit: nbins bins of width 2 sqrt(2) / nbins on [-sqrt(2), sqrt(2)]."""
return -math.sqrt(2.0), 2.0 * math.sqrt(2.0) / nbins
def dd_project_view(img, c, sn, s0, w, nbins):
"""The bin values of one view."""
out = [0 * w] * nbins
for b, i, j, wt in view_weights(len(img), c, sn, s0, w, nbins):
out[b] += wt * img[i][j]
return out # @line L11
def dd_project(img, angles, nbins):
"""The sinogram as a flat list: entry k * nbins + b holds angle k and bin b."""
s0, w = detector(nbins)
out = []
for theta in angles:
out.extend(dd_project_view(img, math.cos(theta), math.sin(theta), s0, w, nbins))
return out
def dd_back_project(n, angles, nbins, values):
"""The exact transpose of dd_project: each weight carries its bin value back to its pixel."""
s0, w = detector(nbins)
out = [[0.0] * n for _ in range(n)]
for k, theta in enumerate(angles):
for b, i, j, wt in view_weights(n, math.cos(theta), math.sin(theta), s0, w, nbins):
out[i][j] += wt * values[k * nbins + b]
return out
def dd_matrix(n, angles, nbins):
"""The system matrix as sparse rows of (column, weight) pairs, column i * n + j."""
s0, w = detector(nbins)
rows = []
for theta in angles:
acc = [dict() for _ in range(nbins)]
for b, i, j, wt in view_weights(n, math.cos(theta), math.sin(theta), s0, w, nbins):
acc[b][i * n + j] = acc[b].get(i * n + j, 0.0) + wt
rows.extend(sorted(d.items()) for d in acc)
return rows
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_distance_driven_projector.py 96 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/distance-driven-projector/. The authors are listed in prov/MVREDC.jsonl.
import math
import random
from fractions import Fraction as F
import imgkit as ik
from distance_driven_projector import (
dd_back_project,
dd_matrix,
dd_project,
dd_project_view,
detector,
view_weights,
)
def test_worked_example() -> None:
# n = 2, cos = 4/5, sin = 3/5, four bins of width 1/2 on [-1, 1]
w = view_weights(2, F(4, 5), F(3, 5), F(-1), F(1, 2), 4)
assert sorted(w) == sorted([
(1, 0, 0, F(5, 4)), (2, 0, 0, F(3, 4)), (2, 0, 1, F(1, 2)), (3, 0, 1, F(5, 4)),
(0, 1, 0, F(5, 4)), (1, 1, 0, F(1, 2)), (1, 1, 1, F(3, 4)), (2, 1, 1, F(5, 4)),
])
p = dd_project_view([[1, 2], [3, 4]], F(4, 5), F(3, 5), F(-1), F(1, 2), 4)
assert p == [F(15, 4), F(23, 4), F(27, 4), F(5, 2)]
# the detector misses 1/8 of pixel (0, 1) and 1/8 of pixel (1, 0)
assert F(1, 2) * sum(p) == 10 - F(2, 8) - F(3, 8)
def test_mass_is_conserved_exactly() -> None:
rng = random.Random(1)
n = 6
img = [[F(rng.randint(0, 9)) for _ in range(n)] for _ in range(n)]
mass = sum(sum(row) for row in img) * F(2, n) ** 2
s0, w, nbins = F(-3, 2), F(1, 4), 12
for c, sn in ((F(4, 5), F(3, 5)), (F(-3, 5), F(4, 5)), (F(12, 13), F(-5, 13)), (F(5, 13), F(12, 13)), (F(1), F(0))):
p = dd_project_view(img, c, sn, s0, w, nbins)
assert w * sum(p) == mass
def test_constant_image_has_no_ripple() -> None:
n, nbins = 32, 23
angles = [0.0, 0.3, 1.2, 2.0]
one = [[1.0] * n for _ in range(n)]
p = dd_project(one, angles, nbins)
q = ik.sp_matvec(ik.parallel_beam_matrix(n, angles, nbins), ik.flatten(one))
s0, w = detector(nbins)
ripple = 0.0
for k, theta in enumerate(angles):
c, sn = abs(math.cos(theta)), abs(math.sin(theta))
for b in range(nbins):
s = s0 + (b + 0.5) * w
if abs(s) + w / 2 < max(c, sn) - min(c, sn):
assert abs(p[k * nbins + b] - 2.0 / max(c, sn)) < 1e-12
ripple = max(ripple, abs(q[k * nbins + b] - 2.0 / max(c, sn)))
# the pixel-driven projector of imgkit has a ripple on the same bins
assert ripple > 1e-3
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 = dd_project(x, angles, nbins)
aty = dd_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, 3.0]
x = [[rng.random() for _ in range(n)] for _ in range(n)]
a = ik.sp_matvec(dd_matrix(n, angles, nbins), ik.flatten(x))
b = dd_project(x, angles, nbins)
assert max(abs(p - q) for p, q in zip(a, b)) < 1e-12
def test_disk_projection() -> None:
n, nbins = 32, 23
angles = [k * math.pi / 8 for k in range(8)]
p = dd_project(ik.disk_phantom(n, 0.5), angles, nbins)
s0, w = detector(nbins)
for k in range(len(angles)):
for b in range(nbins):
if abs(s0 + (b + 0.5) * w) < 0.35:
# the average of the analytic projection 2 sqrt(1/4 - s^2) over the bin
m = 64
avg = sum(2.0 * math.sqrt(max(0.0, 0.25 - (s0 + (b + (r + 0.5) / m) * w) ** 2)) for r in range(m)) / m
assert abs(p[k * nbins + b] - avg) < 2.0 / n
History
Bruno De Man and Samit Basu presented the distance-driven method in 2002 at the IEEE Nuclear Science Symposium and Medical Imaging Conference. They argued that the pixel-driven projector is a poor forward projector and the ray-driven projector a poor back projector, and that the distance-driven method is good in both directions at a similar cost. Their 2004 paper in Physics in Medicine and Biology gave the 3D form for cone-beam and helical CT. Later work moved the method to GPUs, and Long, Fessler and Balter in 2010 refined its rectangular footprint into the separable footprint projector.
References
- Bruno De Man and Samit Basu, Distance-driven projection and backprojection, 2002 IEEE Nuclear Science Symposium Conference Record, vol. 3, 2002, pp. 1477 to 1480 (the 2D method, the comparison with pixel-driven and ray-driven projectors)
- 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 3D form with the overlaps computed separately in the two detector directions; general locator)
- A. C. Kak and M. Slaney, Principles of Computerized Tomographic Imaging, SIAM Classics in Applied Mathematics 33, 2001, Chapter 7, algebraic reconstruction algorithms (the system matrix of the discrete model y = A x)
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 MVREDC Edit this page History Report an error Markdown