Parallel Beam Filtered Backprojection (FBP)
This example demonstrates 2D parallel beam filtered backprojection (FBP) reconstruction using the ParallelProjectorFunction and ParallelBackprojectorFunction from diffct_mlx.engine.
Overview
Parallel beam FBP is the standard analytical reconstruction method for 2D parallel beam CT. This example shows how to:
Configure parallel beam geometry parameters
Generate synthetic projection data using the Shepp-Logan phantom
Apply ramp filtering in the frequency domain
Perform backprojection to reconstruct the image
Visualize and evaluate reconstruction results
Mathematical Background
Parallel Beam Geometry
In parallel beam CT, X-rays are collimated into parallel beams. The projection at angle \(\theta\) and detector position \(t\) is given by the Radon transform:
where \(f(x,y)\) is the 2D attenuation coefficient distribution.
Filtered Backprojection Algorithm
The FBP reconstruction consists of three sequential steps:
Forward Projection: Compute sinogram using the Radon transform
Ramp Filtering: Apply frequency domain filter \(H(\omega) = |\omega|\)
Backprojection: Reconstruct using filtered projections
The complete FBP formula is:
where \(p_f(t, \theta)\) is the filtered projection:
Implementation Steps
Phantom Generation: Create Shepp-Logan phantom with 5 ellipses
Forward Projection: Generate sinogram using ParallelProjectorFunction with geometry from
diffct_mlx.engine.circular_trajectory_2d_parallelRamp Filtering: Apply \(H(\omega) = |\omega|\) filter in frequency domain
Backprojection: Reconstruct using ParallelBackprojectorFunction
Normalization: Scale by \(\frac{\pi}{N_{\text{angles}}}\) factor
Shepp-Logan Phantom
The phantom consists of 5 ellipses representing brain tissue structures:
Outer skull: Large ellipse with low attenuation
Brain tissue: Medium ellipse with baseline attenuation
Ventricles: Small ellipses with fluid-like attenuation
Lesions: High-contrast features for reconstruction assessment
Each ellipse is defined by center position, semi-axes, rotation angle, and attenuation coefficient.
1"""Circular-orbit parallel-beam FBP reconstruction (arbitrary-trajectory API).
2
3Uses the analytical helpers ported from the main branch:
4
5 ParallelProjectorFunction.apply # forward projection
6 ramp_filter_1d # ramp filter along detector axis
7 angular_integration_weights # per-view integration weights
8 parallel_weighted_backproject # voxel-driven FBP gather with 1/(2*pi)
9
10Parallel beam has no source, so there is no ``(sid/U)^2`` distance
11weight - the gather kernel simply projects each pixel onto the detector
12along the ray direction and samples the filtered sinogram. The
13analytical ``1/(2*pi)`` Fourier-convention constant is applied inside
14``parallel_weighted_backproject``.
15"""
16
17import math
18import sys
19from pathlib import Path
20
21import numpy as np
22import torch
23import torch.nn.functional as F
24import matplotlib.pyplot as plt
25
26ROOT_DIR = Path(__file__).resolve().parents[2]
27if str(ROOT_DIR) not in sys.path:
28 sys.path.insert(0, str(ROOT_DIR))
29
30from diffct_mlx.engine import (
31 ParallelProjectorFunction,
32 circular_trajectory_2d_parallel,
33 ramp_filter_1d,
34 angular_integration_weights,
35 parallel_weighted_backproject,
36)
37
38
39def shepp_logan_2d(Nx, Ny):
40 phantom = np.zeros((Ny, Nx), dtype=np.float32)
41 ellipses = [
42 (0.0, 0.0, 0.69, 0.92, 0.0, 1.0),
43 (0.0, -0.0184, 0.6624, 0.8740, 0.0, -0.8),
44 (0.22, 0.0, 0.11, 0.31, -18.0, -0.8),
45 (-0.22, 0.0, 0.16, 0.41, 18.0, -0.8),
46 (0.0, 0.35, 0.21, 0.25, 0.0, 0.7),
47 ]
48 cx = Nx * 0.5
49 cy = Ny * 0.5
50 ys, xs = np.mgrid[0:Ny, 0:Nx].astype(np.float32)
51 xn = (xs - cx) / (Nx / 2)
52 yn = (ys - cy) / (Ny / 2)
53 for (x0, y0, a, b, angdeg, ampl) in ellipses:
54 th = math.radians(angdeg)
55 xp = (xn - x0) * math.cos(th) + (yn - y0) * math.sin(th)
56 yp = -(xn - x0) * math.sin(th) + (yn - y0) * math.cos(th)
57 mask = (xp * xp) / (a * a) + (yp * yp) / (b * b) <= 1.0
58 phantom[mask] += ampl
59 return np.clip(phantom, 0.0, 1.0)
60
61
62def main():
63 Nx, Ny = 256, 256
64 phantom = shepp_logan_2d(Nx, Ny)
65
66 # Parallel FBP integrates over half a rotation (0 to pi) because each
67 # ray and its 180-degree twin are the same measurement.
68 num_angles = 360
69 num_detectors = 512
70 detector_spacing = 1.0
71 voxel_spacing = 1.0
72
73 device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
74 image_torch = torch.tensor(phantom, device=device, dtype=torch.float32)
75
76 ray_dir, det_origin, det_u_vec = circular_trajectory_2d_parallel(
77 num_angles, device=device
78 )
79 angles_torch = torch.linspace(
80 0.0, math.pi, num_angles + 1, device=device
81 )[:-1]
82
83 # ---- 1. forward projection ----
84 sinogram = ParallelProjectorFunction.apply(
85 image_torch, ray_dir, det_origin, det_u_vec,
86 num_detectors, detector_spacing, voxel_spacing,
87 )
88
89 # ---- 2. ramp filter (no cosine pre-weight for parallel) ----
90 sinogram_filt = ramp_filter_1d(
91 sinogram,
92 dim=1,
93 sample_spacing=detector_spacing,
94 pad_factor=2,
95 window="hann",
96 ).contiguous()
97
98 # ---- 3. angular integration weights ----
99 # Parallel beam covers [0, pi] so there is no redundancy factor.
100 d_beta = angular_integration_weights(
101 angles_torch, redundant_full_scan=False
102 ).view(-1, 1)
103 sinogram_filt = sinogram_filt * d_beta
104
105 # ---- 4. voxel-driven FBP gather + 1/(2*pi) constant ----
106 reconstruction_raw = parallel_weighted_backproject(
107 sinogram_filt, ray_dir, det_origin, det_u_vec,
108 detector_spacing, Ny, Nx, voxel_spacing=voxel_spacing,
109 )
110 reconstruction = F.relu(reconstruction_raw)
111
112 raw_mse = torch.mean((reconstruction_raw - image_torch) ** 2).item()
113 clamped_mse = torch.mean((reconstruction - image_torch) ** 2).item()
114 print("Parallel Beam FBP example (arbitrary-trajectory API)")
115 print(f" Raw MSE: {raw_mse:.6f}")
116 print(f" Clamped MSE: {clamped_mse:.6f}")
117 print(f" Raw reco range: [{reconstruction_raw.min().item():.4f}, "
118 f"{reconstruction_raw.max().item():.4f}]")
119 print(f" Phantom range: [{float(phantom.min()):.4f}, "
120 f"{float(phantom.max()):.4f}]")
121
122 sinogram_cpu = sinogram.detach().cpu().numpy()
123 reco_cpu = reconstruction.detach().cpu().numpy()
124
125 plt.figure(figsize=(12, 4))
126 plt.subplot(1, 3, 1)
127 plt.imshow(phantom, cmap="gray")
128 plt.title("Phantom")
129 plt.axis("off")
130 plt.subplot(1, 3, 2)
131 plt.imshow(sinogram_cpu, cmap="gray", aspect="auto")
132 plt.title("Parallel Sinogram")
133 plt.axis("off")
134 plt.subplot(1, 3, 3)
135 plt.imshow(reco_cpu, cmap="gray")
136 plt.title("Parallel Reconstruction")
137 plt.axis("off")
138 plt.tight_layout()
139 plt.show()
140
141
142if __name__ == "__main__":
143 main()