OPTICS & SIGNAL NOTE · EXPECTATION-MAXIMIZATION ALIGNMENT

7 minute read

Four-panel apples-to-apples comparison of 90 real 30-second frames of M104 (the Sombrero Galaxy) captured on a Canon EOS 700D: (a) Final 90-frame EM alignment with synthetic flat and dispersion fix shows a sharp dust lane and core; (b) 90-frame EM without dispersion fix shows atmospheric chromatic dispersion; (c) 90-frame star registration with Winsorized clipping fails with only 1 star detected; (d) 90-frame naive unaligned average smears the galaxy diagonally
90 real 30-second exposures (45 minutes total, Canon EOS 700D; raw frames courtesy of Nick Rahne) of M104, the Sombrero Galaxy. Star registration (c) fails when only 1 faint star is visible, whereas Expectation-Maximization (a, b) locks cleanly onto the galaxy itself and even reveals real atmospheric chromatic dispersion fixed in (a).

Standard astrophotography stackers need bright stars to align your frames. On this 45-minute capture of M104 (the Sombrero Galaxy), DeepSkyStacker found 0 stars and my custom star detector found just 1, smearing the galaxy almost as badly as an unaligned average ((c) vs. (d)).

I tried Expectation-Maximization (EM), a technique borrowed from cryo-electron microscopy (which faces the exact same challenge of aligning noisy, drifting snapshots), and found a drastic improvement (see the results summary below). Here is how to try it yourself, what makes it different, and what it looks like on real sky data.

NOTE: My ideas, astrophotography data, and analysis, aided by Gemini Neon (medium) for derivations, code, and plotting. Full C++ and Python implementation in jrmlhermitte/astro_stacker · Download the 4-page technical paper (PDF).


1. Try It Yourself

The full C++ stacker is open-source in jrmlhermitte/astro_stacker:

git clone https://github.com/jrmlhermitte/astro_stacker.git
cd astro_stacker/cpp_stacker && cmake -B build && cmake --build build -j

# 1. Align & stack star-starved frames into a linear 32-bit TIFF
./build/astro_stacker --lights /path/to/lights --darks /path/to/darks \
  --reg-mode em-image --stack-mode em --flat-mode full-iter \
  --out-tif stack.tif

# 2. Stretch the linear TIFF into a natural-color JPG/PNG (with RGB dispersion fix)
python3 ../scripts/stretch_natural_color.py --in-tif stack.tif \
  --out-full stack.jpg --align-rgb

2. What Is Different?

In my previous post, we saw that star-based Gaussian fitting is great when bright guide stars are in view, while raw pairwise cross-correlation pays a heavy quadratic \(N_1 N_2\) noise floor.

EM bridges the gap by changing what you align against:

Two-panel visual diagram comparing Standard Star Registration (finding and tracking a single bright star across drifted frames, which fails when bright stars disappear) against EM Alignment (pooling the entire galaxy, nebula, and all faint stars into an iterative soft-weighted consensus stack)
Left: standard star registration tracks bright point-like stars, which is fast and sharp until bright stars disappear. Right: EM pools every pixel (galaxy, nebula, and faint stars) into an iterative soft-weighted consensus stack, working even when star detectors report 0 stars.
  • Standard Star Registration: Detects bright stars in each frame, matches star triangles, and shifts frames to line up those star coordinates. Fast and razor-sharp on star-rich fields, but helpless when stars vanish.
  • EM Alignment: Uses every pixel in the frame (the galaxy, nebula, and all faint stars together). It iteratively cross-correlates each frame against the running average stack (using fast 2D FFTs) and combines plausible shifts with soft probability weights instead of a brittle all-or-nothing argmax.

3. The Results: Real Sky, Synthetic Stress Tests, and Gotchas

Real Sky: Full-Sensor M104 + Synthetic Flat-Fielding

Zooming out to the full sensor on Nick Rahne’s 90-frame M104 capture, EM locks onto the galaxy cleanly across the whole night while blind synthetic flat-fielding removes vignetting and dust motes:

Full-sensor 90-frame EM-aligned stack of M104 (the Sombrero Galaxy) with synthetic flat-fielding and dispersion fix, showing an evenly flattened background across the entire frame
Full-sensor 90-frame EM + synthetic flat-field stack of M104 (raw frames courtesy of Nick Rahne), with vignetting and dust motes cleanly removed across the whole frame.

Real Sky: Star-Rich Sanity Checks (M31, M51, & M42)

When plenty of bright stars are in view on untouched real-sky captures, EM and star registration produce virtually indistinguishable results, so star registration still wins on bright starfields because it is dramatically faster and naturally handles arbitrary 360° rotations:

Three-panel comparison of 21 real frames of M31 (Andromeda Galaxy): Star-Reg + Winsorized, Full-Image EM-Reg + EM, and their Residual showing sub-pixel agreement
Real-sky M31 (21 frames, Canon EOS 1100D): Star-Reg vs. Full-Image EM and their residual, agreeing to a tenth of a pixel.
Real-sky stack of M51, the Whirlpool Galaxy (4 x 300s, Canon EOS 1100D at Custer Observatory), showing crisp spiral arms, companion galaxy, and plenty of bright field stars
Real-sky M51 (4 × 300 s, Canon EOS 1100D, Custer Observatory): plenty of bright field stars, where star registration and EM yield identical image quality.
Real-sky EM-aligned crop of M42 (the Orion Nebula) captured at Custer Observatory (11 x 29s + 2 x 59s, Canon EOS 1100D), showing the bright Trapezium stars and surrounding gas clouds
Real-sky M42 (Orion Nebula, Custer Observatory), aligned cleanly with EM across large drift.

Synthetic Stress Tests: Pushing M57 Into Pure Static

To see where EM’s limit actually sits, I ran two synthetic noise stress tests based on M57 (the Ring Nebula). First, injecting heavy synthetic skyglow noise into real Canon EOS 1100D frames of M57 causes star registration to detect zero stars and fail, while EM still locks directly onto the nebula itself:

Three-panel noise-injected M57 Ring Nebula stress test: left panel shows a single real frame with heavy synthetic skyglow noise added and 0 stars detected; middle panel shows star registration failing; right panel shows EM registration locking directly onto the nebula
Synthetic noise stress test on real Canon EOS 1100D frames of M57 (heavy skyglow noise added): star registration detects 0 stars and fails, while EM locks onto the nebula itself.

Second, in a fully synthetic 200-frame benchmark where a single frame looks like pure TV static, both star registration and pairwise FFT cross-correlation collapse completely, while Soft-EM pulls M57 cleanly out of the noise:

Six-panel fully synthetic photon-starved M57 Ring Nebula benchmark across 200 frames at peak pixel SNR 0.22: (a) Ground Truth M57; (b) single raw frame looks like pure static; (c) unaligned mean is a featureless blob; (d) star registration fails; (e) pairwise FFT cross-correlation fails; (f) Soft-EM reconstructs the Ring Nebula cleanly
Fully synthetic 200-frame photon-starved M57 benchmark where a single frame (b) is pure static. Star registration (d) and pairwise FFT (e) both fail; Soft-EM (f) pulls the ring cleanly out of the noise.

Gotcha: The Floating Ghost Galaxy

EM is not magic. When my first M104 run capped the coarse shift search too tightly, the final 30 frames (taken after a mid-session break with large drift) couldn’t reach the main galaxy. Instead of blurring out, those 30 frames locked onto each other, forming a floating ghost galaxy above M104! Widening the search window on the same FFT canvas eliminated the ghost completely:

Crop of the 90-frame M104 stack when the coarse EM search radius was capped too tightly: a crisp purple ghost image of the Sombrero Galaxy floats above the main galaxy because the final 30 drifted frames locked onto each other in a secondary cluster
Multi-modal EM ghosting under a tight search cap: the final 30 drifted frames locked onto each other in a secondary local maximum, creating a ghost galaxy above M104.

How do you catch subtle EM artifacts like ghosting or noise-locking automatically? In cryo-electron microscopy, researchers routinely split the dataset into two independent halves (e.g., odd vs. even frames), run EM separately on each half, and verify that both reconstructions agree. The same half-set sanity check works nicely for astrophotography too: real galaxy structure shows up identically in both halves, while trapped noise or drift artifacts immediately stand out.

Results Summary

To put all of these real-sky captures and synthetic stress tests side by side, the table below compares standard star registration against EM alignment across every target above:

Target & Dataset Frames & Drift Star Registration EM Alignment Key Takeaway
M104 (Sombrero) (raws: Nick Rahne) 90 × 30 s (>350 px drift, 3.1° rot.) Failed (1/90 stars, SNR = 11.5) 90/90 locked (SNR = 264.0, Kish N_eff = 89.5) 23× SNR gain; sky MAD 4.14 → 2.00 (exact \(\sqrt{90/20}\) Poisson scaling); flat uniformity 0.858 → 0.971; dispersion ~9 px → ±0.15 px
M57 (Synthetic Static) 200 frames (peak pixel SNR = 0.22) Failed (12.6 px err, r = 0.32) Recovered (3.77 px err, r = 0.95) Pairwise FFT also fails (18.0 px, r = 0.23); Soft-EM pulls ring out of pure static
M57 (Real +1500 ADU) 18 frames (Canon 1100D) Failed (0/18 locked, 19.4 px err) 16/18 locked (1.53 px err) EM locks directly onto extended nebula when stars vanish
M31 (Andromeda) 21 frames (Canon 1100D) SNR = 114.88 SNR = 113.95 Matches star registration to 0.106 px
M51 (Whirlpool) 4 × 300 s (Custer Obs.) SNR = 87.0 SNR = 86.1 Identical quality; star registration is ~250× faster
M42 (Orion Nebula) 11 × 29 s + 2 × 59 s (>100 px drift) Crisp Crisp Clean alignment across bright nebulosity and Trapezium core

4. Under the Hood (For the Curious)

If you want to see why EM iterates and how the math connects back to cross-correlation, here is the short version (full details in em_registration.cpp and the 4-page PDF):

Step 1 (E-step: recalculate shift weights \(q_k(\delta)\)): Holding the current consensus template \(\hat{S}^{(t)}\) fixed, cross-correlate frame \(I_k\) via 2D FFT against the leave-one-out stack \(\hat{S}^{(t)}_{-k}\) (excluding frame \(k\) so it never locks onto its own shot noise, avoiding “Einstein from noise”). Under Gaussian skyglow variance \(\sigma_k^2\), the log-likelihood of shift \(\delta\) is directly proportional to the cross-correlation \(C_k(\delta) = \sum_x I_k(x + \delta)\,\hat{S}^{(t)}_{-k}(x)\), giving soft weights:

\[q_k^{(t)}(\delta) \propto \exp\!\left(\frac{C_k(\delta) - C_{\max}}{\sigma_k^2}\right)\]

Step 2 (M-step: recalculate a cleaner template \(\hat{S}^{(t+1)}\)): Holding \(q_k^{(t)}(\delta)\) fixed, shift and average all frames weighted by \(q_k^{(t)}(\delta)\) to cancel out skyglow noise and produce a sharper template \(\hat{S}^{(t+1)}\).

Why iterate? Because \(\hat{S}^{(1)}\) is now much cleaner than the noisy starting guess \(\hat{S}^{(0)}\), re-running the E-step gives sharper shift weights \(q_k^{(1)}(\delta)\), which yields an even sharper \(\hat{S}^{(2)}\). Mathematically, each pass climbs a guaranteed lower-bound hill (ELBO) toward a local likelihood peak (like walking toward a dim beacon in thick fog: each step closer makes the beacon clearer, though a cramped search window can trap frames in a local “ghost” peak).

  • Fundamental limit: Even optimal EM still hits the Multi-Reference Alignment sample-complexity wall at very low SNR (\(N \propto 1/\text{SNR}^4\) for symmetric/known shapes, up to \(1/\text{SNR}^6\) for arbitrary unknown shapes; Perry et al., 2019).
  • Practical rule of thumb: Use star registration on bright starfields (~250× faster), EM alignment when stars disappear (M104, narrowband, photon-starved data), and temporal EM mixture stacking once aligned as a soft, noise-weighted upgrade to Winsorized sigma clipping.

Updated:


Comments/Suggestions?

NOTE: You'll need to have a github account and give giscus comment access. This is necessary to allow it to post a comment on your behalf. If you don't feel comfortable giving giscus access, please find the corresponding topic and manually comment here.