Algorithmadvanced
Drizzle
Also called variable-pixel linear reconstruction.
Combine dithered undersampled images by shrinking each input pixel to a smaller drop and adding its value to the output pixels it overlaps, weighted by overlap area. It keeps flux.
- Time
- Θ(K n c + m) worst · average · best
- Space
- Θ(m) extra
- Where
- K = the number of frames; c = the most output pixels one drop overlaps; m = the number of output pixels; n = the number of pixels per input frame
- Model
- Real RAM
- Properties
- deterministichandles bad pixelsnot iterativekeeps fluxlinear
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Andrew S. Fruchter, Richard N. Hook, 2002
Drizzle, formally variable-pixel linear reconstruction, combines several dithered images of the same field into one image on a finer grid. Fruchter and Hook built it for the Hubble Deep Field, whose camera pixels were too large for the PSF of the telescope. Each input pixel is mapped onto the output grid by the known geometric transform of its frame and shrunk to a smaller square, the drop, with the same center. The drop adds its value to each output pixel that it overlaps, weighted by the overlap area and by a per-pixel weight; at the end each output pixel is divided by its total weight. The result is a weighted mean, so the surface brightness and the weighted flux are kept exactly, bad pixels and cosmic rays are left out by a zero weight, and the output is a linear function of the data. The ratio of the drop size to the input pixel, the pixfrac, trades resolution against holes and noise. With a pixfrac of 1 and integer shifts drizzle is shift-and-add; with a small pixfrac and a complete set of subpixel dithers it is interlacing. It does not deblur: it removes the extra blur of the large pixel only as far as the dithers allow, and it does not undo the PSF of the optics. It solves a version of multi-frame super-resolution where photometric accuracy matters more than sharpness.
In plain words
Think of each pixel of a camera image as a square tile with a number on it, its brightness. You have several photos of the same sky, each moved by a fraction of a pixel. Lay out a fine grid of small output squares. Take each tile of each photo, shrink it around its center to a smaller drop, and place it on the fine grid where it belongs. Each small square that the drop touches gets a share of the brightness, in proportion to how much of the square the drop covers. Keep a second count of how much drop each small square received. At the end, divide the first sum by the second. Small drops keep the picture sharp but can leave empty squares; large drops fill every square but blur the picture a little.
The problem
There are input frames of the same scene, each with pixels. Pixel of a frame has the value in counts and a weight (an inverse variance, or for a bad pixel or a cosmic ray hit). The geometric transform of each frame to the output frame is known; it comes from the pointing of the telescope or from image registration, and it may include the distortion of the camera. The output is an image on a grid of square pixels of side , in units of the input pixel side, with for a finer grid. The goal is an output image in counts per output pixel that keeps the flux of the input and is as sharp as the dithers allow.
The algorithm
The code and the pseudocode use a shift for each frame, so each drop stays an axis-aligned square. The general method maps the four corners of each drop through the transform and computes the area of overlap of a quadrilateral with each output pixel.
DRIZZLE(frames, shifts, weights, s, p) ▷ s: output pixel side, p: drop side (pixfrac)- 1
W ← 0, V ← 0 on the output grid - 2
for each frame k and each input pixel i with value d and weight w > 0 - 3
drop ← square of side p around the center of pixel i, shifted by shift_k - 4
for each output pixel o that the drop overlaps - 5
a ← area(drop ∩ o) - 6
W_o ← W_o + a·w, V_o ← V_o + a·w·d - 7
for each output pixel o - 8
I_o ← s² · V_o / W_o if W_o > 0, else 0 ▷ counts per output pixel - 9
return I, W
Line L8 turns counts per input pixel into counts per output pixel with the factor , the ratio of the pixel areas. The weight image is an output too: it shows where the output is well covered, and it is the weight for a later drizzle or for photometry.
Example
Take two frames of one row with three pixels each, shifted by and shifted by along the row. The output pixels have the side , so the output has two rows, and the two rows are equal. The drop of pixel of is centered at and that of at . One output row (columns to , in counts per output pixel) for three pixfracs, computed in exact arithmetic:
| output | weight per column | |
|---|---|---|
With each drop covers exactly one output column. The output is the interlaced sequence divided by , and the peak is the sharpest. With each drop covers three output pixels, the peak falls to , and the edges of the field get partial coverage. In each case : the totals over both output rows are , and for , and the input total is .
Correctness
The full proof is in proofs/correctness.md. The facts, all theorems about the computation:
- Overlap. For axis-aligned squares, the overlap area is the product of the overlaps of the two side intervals, and the loop of line L4 finds every output pixel with a positive overlap.
- Weighted mean. Where , is a convex combination of the values of the drops that touch . A flat input of counts per pixel gives counts per output pixel everywhere it is covered: the surface brightness is kept.
- Weighted flux. When every drop lies inside the output grid, and .
- Linearity. For fixed geometry and weights, is linear in the data.
- Special cases. With and integer shifts drizzle is shift-and-add. With and four dithers at half-pixel offsets, each drop is one output pixel and the result is the interlaced image divided by .
Proof: Drizzle is a weighted mean of the drops, it keeps the weighted flux, and its special cases are shift-and-add and interlacingfull
Setting. Input pixel (of any frame) has the value (counts per input pixel), the weight and, after the geometric transform, the drop : a square of side around the transformed pixel center. Here the transform is a shift, so is an axis-aligned square of area . Output pixel is the square of side . Lines L1 to L8 compute
The code adds the drops one at a time, so after all drops the two sums are the ones above; the order of the additions does not change them.
Claim 1 (overlap areas). For axis-aligned squares, , where and are the lengths of the intersections of the projections on the two axes, and . The loop of line L4 visits every with .
Proof. The intersection of two axis-aligned rectangles is the product of the intersections of their sides, which are intervals; the length of is the formula. Output column covers , and it meets in a set of positive length only if and , that is ; the same holds for the rows.
The test compares the areas with a brute force count of lattice cells of side , which is exact when all edges lie on the lattice.
Claim 2 (weighted mean). If , is a convex combination of the values of the drops that overlap with . In particular, if all such equal , then .
Proof. The coefficients are nonnegative and sum to .
So a flat input of counts per input pixel gives counts per output pixel: the surface brightness is kept, for any shifts, any and any weights.
Claim 3 (weighted flux). If every drop lies inside the output grid, then
Proof. For , , and for both sides are because then for all . Sum over and swap the sums: , because the output pixels tile the plane and the drop lies inside the grid. The second identity is the same with .
With equal weights, the mean input value: the flux of the input, measured in counts per output pixel, is kept in the weighted sense. The plain sum is the total flux only where the output pixels are covered with a uniform weight.
Claim 4 (linearity). For fixed shifts, , and weights, is a linear function of the data , and does not depend on .
Proof. and do not depend on , and is a fixed linear combination of the .
Claim 5 (shift-and-add). With , integer shifts and unit weights, is the mean of the input values whose pixels land exactly on .
Proof. A drop of side shifted by integers is exactly one output pixel, so and .
Claim 6 (interlacing). Let and use four frames with the shifts for and a fixed . Then the drop of pixel of frame is exactly one output pixel, and on the interlaced grid.
Proof. The center of the drop is at , so the drop covers , which is the output column when is an integer. The same holds for the rows. So for exactly one , and .
So drizzle with a small pixfrac and a complete set of half-pixel dithers puts each input sample on its own output pixel, with no smoothing by the input pixel shape beyond what the detector already did. With the same frames give a smoother output, because each input pixel covers several output pixels.
Complexity
In the real-RAM model, each drop overlaps at most output pixels, and each overlap costs for a square. So the drops cost , and the final division costs for output pixels: in total, with extra space for and . A general transform needs the area of a quadrilateral clipped to a square, still per pair. There is no iteration, so the cost is fixed in advance.
Properties
- Keeps flux and surface brightness (Claims 2 and 3). This is why astronomers use it for photometry.
- Linear. The output is a fixed linear map of the input for fixed geometry and weights, so noise and artifacts can be traced. It does not fit a model and does not deconvolve.
- Bad pixels drop out. A zero weight removes a pixel from every sum. The output stays correct where other frames cover the same place.
- Correlated noise. A drop larger than an output pixel puts the same input noise into several output pixels, so neighbor output pixels have correlated noise. Fruchter and Hook give a correction factor for the noise measured in an aperture.
- The pixfrac is a choice. A smaller pixfrac gives less smoothing and less correlated noise, but more variation in the weight and holes where no drop lands. The choice depends on the number of dithers and their pattern; it is tuned, not derived.
Variants and improvements
- General geometry. Map the corners of each drop through the full transform, including the distortion of the camera, and clip polygons. Production codes for the Hubble Space Telescope do this.
- Blot and cosmic ray rejection. Drizzle each frame alone, take a median of the drizzled frames, map the median back to the frame of each input ("blot"), and mark the pixels that differ much from it as cosmic rays with weight . Then drizzle again.
- Kernels. Replace the square drop by a point (the limit , interlacing), a Gaussian or a Lanczos kernel. Only the square and the point give the exact flux identity of Claim 3 with an exact overlap area.
- Deconvolution after drizzle. Drizzle does not undo the optical PSF. A deconvolution step, or a joint method such as iterative back-projection, can follow.
When to use it
Use drizzle to combine dithered, undersampled frames when the flux must be kept for photometry, when there are bad pixels and cosmic rays, and when the frames have different weights or a distorted geometry. It is the standard way to combine Hubble images. When the goal is maximum sharpness and the noise is low, a deconvolving method such as iterative back-projection or a regularized least squares fit gives sharper results, at the cost of a nonlocal and less predictable noise. When the frames are not undersampled, plain resampling and averaging are enough.
Pitfalls
- Holes. With a small pixfrac and few dithers, some output pixels get no drop. Check the weight image , and raise the pixfrac until has no zeros in the area of interest.
- Wrong geometry. An error in a shift moves the drops of a whole frame and blurs or doubles every source.
- Reading the output as uncorrelated. The noise of neighbor output pixels is correlated when . Error bars from the pixel to pixel scatter are too small.
- Units. The output is in counts per output pixel. Forgetting the factor changes every flux by .
- Edges. The plain sum equals the input flux only where the coverage is uniform. Near the edge of the field use the weighted identity, or cut the edge.
Implementations
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/drizzle/. The authors are listed in prov/GWCHWD.jsonl.
"""Drizzle (variable-pixel linear reconstruction) for shifted frames.
Coordinates: an input pixel (i, j) of a frame covers the unit square
[j, j + 1] x [i, i + 1] of its own frame (x along the columns, y along the
rows). A frame with the shift (dx, dy) puts that square at
[j + dx, j + 1 + dx] x [i + dy, i + 1 + dy] in the output frame. The output
grid has pixels of side s (in input pixel units): output pixel (I, J) covers
[J s, (J + 1) s] x [I s, (I + 1) s].
Each input pixel is shrunk to a drop: a square of side p (the pixfrac times the
input pixel side) with the same center. The drop adds its value, times its
overlap area and its weight, to each output pixel it overlaps.
The values of an input frame are counts per input pixel. The output is in
counts per output pixel: I_o = s^2 (sum a w d) / (sum a w). Works with float
and with fractions.Fraction values; with Fractions all results are exact.
"""
import math
def overlap_1d(a0, a1, b0, b1):
"""The length of the intersection of the intervals [a0, a1] and [b0, b1]."""
lo = a0 if a0 > b0 else b0
hi = a1 if a1 < b1 else b1
return hi - lo if hi > lo else 0 * (hi - lo)
def drop_footprint(i, j, shift, p):
"""The drop of input pixel (i, j) in the output frame: (x0, x1, y0, y1)."""
dx, dy = shift
mid = (1 + 0 * p) / 2 # 1/2, a Fraction when p is a Fraction
cx = j + dx + mid
cy = i + dy + mid
half = p / 2
return cx - half, cx + half, cy - half, cy + half
def drizzle(frames, shifts, s, p, out_shape, weights=None):
"""Drizzle the frames onto an output grid of out_shape = (M1, M2) pixels of side s.
frames is a list of images; shifts[k] = (dx, dy) places frame k in the
output frame; p is the drop side (pixfrac, in input pixel units);
weights[k] is an optional weight image for frame k (0 marks a bad pixel).
Returns (I, W): the output image in counts per output pixel, and the
weight image W_o = sum a w. An output pixel with W_o = 0 gets the value 0.
"""
m1, m2 = out_shape
zero = 0 * s
wsum = [[zero] * m2 for _ in range(m1)] # @line L1
vsum = [[zero] * m2 for _ in range(m1)] # @line L1
for k, frame in enumerate(frames): # @line L2
wk = weights[k] if weights is not None else None
for i, row in enumerate(frame): # @line L2
for j, d in enumerate(row): # @line L2
w = 1 if wk is None else wk[i][j]
if w == 0:
continue
x0, x1, y0, y1 = drop_footprint(i, j, shifts[k], p) # @line L3
jlo = max(0, math.floor(x0 / s)) # @line L4
jhi = min(m2 - 1, math.ceil(x1 / s) - 1) # @line L4
ilo = max(0, math.floor(y0 / s)) # @line L4
ihi = min(m1 - 1, math.ceil(y1 / s) - 1) # @line L4
for oi in range(ilo, ihi + 1): # @line L4
ly = overlap_1d(y0, y1, oi * s, (oi + 1) * s)
if ly == 0:
continue
for oj in range(jlo, jhi + 1): # @line L4
lx = overlap_1d(x0, x1, oj * s, (oj + 1) * s)
if lx == 0:
continue
a = lx * ly # @line L5
wsum[oi][oj] += a * w # @line L6
vsum[oi][oj] += a * w * d # @line L6
s2 = s * s
out = [[zero] * m2 for _ in range(m1)]
for oi in range(m1): # @line L7
for oj in range(m2): # @line L7
if wsum[oi][oj] != 0: # @line L8
out[oi][oj] = s2 * vsum[oi][oj] / wsum[oi][oj] # @line L8
return out, wsum # @line L9
def shift_and_add(frames, shifts, out_shape):
"""Place each pixel of each frame at the output pixel of its shifted position and average.
The shifts must be integers. This is drizzle with s = p = 1.
"""
m1, m2 = out_shape
tot = [[0] * m2 for _ in range(m1)]
cnt = [[0] * m2 for _ in range(m1)]
for frame, (dx, dy) in zip(frames, shifts):
for i, row in enumerate(frame):
for j, d in enumerate(row):
oi, oj = i + dy, j + dx
if 0 <= oi < m1 and 0 <= oj < m2:
tot[oi][oj] += d
cnt[oi][oj] += 1
return [[tot[i][j] / cnt[i][j] if cnt[i][j] else 0 * tot[i][j] for j in range(m2)] for i in range(m1)]
def total_flux(img, weights=None):
"""sum_o W_o I_o, or sum_o I_o if no weights are given."""
if weights is None:
return sum(v for row in img for v in row)
return sum(w * v for rw, rv in zip(weights, img) for w, v in zip(rw, rv))
test_drizzle.py 165 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/drizzle/. The authors are listed in prov/GWCHWD.jsonl.
import random
from fractions import Fraction as F
from drizzle import drizzle, overlap_1d, shift_and_add, total_flux
def rand_frame(rng, n1, n2, lo=0, hi=9):
return [[F(rng.randint(lo, hi)) for _ in range(n2)] for _ in range(n1)]
def brute_drizzle(frames, shifts, s, p, out_shape, q):
"""Drizzle with each overlap area found by counting cells of side 1/q.
Every drop edge and every output pixel edge must lie on the lattice of
step 1/q; then the count of lattice cells whose centers lie in both
squares, times 1/q^2, is the exact overlap area.
"""
m1, m2 = out_shape
wsum = [[F(0)] * m2 for _ in range(m1)]
vsum = [[F(0)] * m2 for _ in range(m1)]
cell = F(1, q)
for frame, (dx, dy) in zip(frames, shifts):
for i, row in enumerate(frame):
for j, d in enumerate(row):
x0 = j + dx + F(1, 2) - p / 2
y0 = i + dy + F(1, 2) - p / 2
steps = int(p * q)
for u in range(steps):
for v in range(steps):
cx = x0 + (u + F(1, 2)) * cell
cy = y0 + (v + F(1, 2)) * cell
oj, oi = int(cx // s), int(cy // s)
if 0 <= oi < m1 and 0 <= oj < m2:
wsum[oi][oj] += cell * cell
vsum[oi][oj] += cell * cell * d
out = [[s * s * vsum[i][j] / wsum[i][j] if wsum[i][j] else F(0) for j in range(m2)] for i in range(m1)]
return out, wsum
def test_overlap_1d():
assert overlap_1d(F(0), F(1), F(1, 2), F(3)) == F(1, 2)
assert overlap_1d(F(0), F(1), F(2), F(3)) == 0
assert overlap_1d(F(1, 4), F(3, 4), F(0), F(2)) == F(1, 2)
assert overlap_1d(0.0, 1.0, 1.0, 2.0) == 0
def test_matches_brute_force_cell_counting():
rng = random.Random(1)
q = 20
for _ in range(4):
n = 3
frames = [rand_frame(rng, n, n) for _ in range(3)]
shifts = [(F(rng.randint(0, 20), q), F(rng.randint(0, 20), q)) for _ in range(3)]
s = F(rng.choice([10, 12, 15]), q)
p = F(rng.choice([6, 10, 14, 20]), q)
out_shape = (int((n + 2) / s) + 1, int((n + 2) / s) + 1)
got = drizzle(frames, shifts, s, p, out_shape)
assert got == brute_drizzle(frames, shifts, s, p, out_shape, q)
def test_weighted_flux_is_kept_exactly():
# sum_o W_o I_o = s^2 p^2 sum_i w_i d_i when every drop lies inside the output grid.
rng = random.Random(2)
for _ in range(5):
n = 4
k = 3
frames = [rand_frame(rng, n, n) for _ in range(k)]
weights = [[[F(rng.choice([0, 1, 1, 2])) for _ in range(n)] for _ in range(n)] for _ in range(k)]
shifts = [(F(rng.randint(0, 9), 7), F(rng.randint(0, 9), 7)) for _ in range(k)]
s = F(rng.choice([1, 2, 3]), 3)
p = F(rng.choice([1, 2, 3]), 3)
m = int((n + 3) / s) + 1
img, wmap = drizzle(frames, shifts, s, p, (m, m), weights)
left = total_flux(img, wmap)
right = s * s * p * p * sum(w * d for fr, wf in zip(frames, weights) for rf, rw in zip(fr, wf) for d, w in zip(rf, rw))
assert left == right
# The total weight is p^2 times the total input weight.
assert sum(v for row in wmap for v in row) == p * p * sum(v for wf in weights for row in wf for v in row)
def test_constant_input_gives_a_constant_output():
c = F(7)
frames = [[[c] * 5 for _ in range(5)] for _ in range(2)]
shifts = [(F(0), F(0)), (F(1, 3), F(2, 5))]
s, p = F(2, 3), F(3, 4)
img, wmap = drizzle(frames, shifts, s, p, (9, 9))
for i in range(9):
for j in range(9):
if wmap[i][j] != 0:
assert img[i][j] == c * s * s
def test_unit_pixels_and_integer_shifts_give_shift_and_add():
rng = random.Random(3)
frames = [rand_frame(rng, 4, 4) for _ in range(3)]
shifts = [(0, 0), (1, 0), (1, 2)]
img, _ = drizzle(frames, [(F(a), F(b)) for a, b in shifts], F(1), F(1), (6, 6))
assert img == shift_and_add(frames, shifts, (6, 6))
def test_four_half_pixel_dithers_interlace_exactly():
# With s = p = 1/2 and the shifts (-1/4 + b/2, -1/4 + a/2), the drop of
# pixel (i, j) of frame (a, b) is exactly output pixel (2 i + a, 2 j + b).
rng = random.Random(4)
n = 4
fine = rand_frame(rng, 2 * n + 2, 2 * n + 2)
frames, shifts = [], []
for a in (0, 1):
for b in (0, 1):
frames.append([[fine[2 * i + a + 1][2 * j + b + 1] for j in range(n)] for i in range(n)])
shifts.append((F(-1, 4) + F(b, 2) + F(1, 2), F(-1, 4) + F(a, 2) + F(1, 2)))
s = p = F(1, 2)
img, wmap = drizzle(frames, shifts, s, p, (2 * n + 2, 2 * n + 2))
for i in range(1, 2 * n + 1):
for j in range(1, 2 * n + 1):
assert wmap[i][j] == F(1, 4)
assert img[i][j] == fine[i][j] / 4
def test_linear_in_the_data():
rng = random.Random(5)
f1 = [rand_frame(rng, 3, 3, -5, 5) for _ in range(2)]
f2 = [rand_frame(rng, 3, 3, -5, 5) for _ in range(2)]
shifts = [(F(0), F(0)), (F(2, 5), F(1, 5))]
s, p = F(1, 2), F(3, 5)
alpha = F(3, 7)
mix = [[[alpha * x + y for x, y in zip(r1, r2)] for r1, r2 in zip(a, b)] for a, b in zip(f1, f2)]
i1, w1 = drizzle(f1, shifts, s, p, (8, 8))
i2, _ = drizzle(f2, shifts, s, p, (8, 8))
im, wm = drizzle(mix, shifts, s, p, (8, 8))
assert wm == w1
assert im == [[alpha * x + y for x, y in zip(r1, r2)] for r1, r2 in zip(i1, i2)]
def test_bad_pixels_are_left_out():
frames = [[[F(1), F(100)], [F(1), F(1)]], [[F(1), F(1)], [F(1), F(1)]]]
weights = [[[1, 0], [1, 1]], [[1, 1], [1, 1]]]
img, wmap = drizzle(frames, [(F(0), F(0)), (F(0), F(0))], F(1), F(1), (2, 2), weights)
assert img == [[1, 1], [1, 1]]
assert wmap == [[2, 1], [2, 2]]
def test_uncovered_output_pixels_have_zero_weight():
frames = [[[F(5)]]]
img, wmap = drizzle(frames, [(F(0), F(0))], F(1, 2), F(1, 2), (2, 2))
# The drop [1/4, 3/4]^2 touches all four output pixels of side 1/2.
assert wmap == [[F(1, 16)] * 2] * 2
img2, wmap2 = drizzle(frames, [(F(0), F(0))], F(1, 2), F(1, 2), (4, 4))
assert wmap2[3][3] == 0 and img2[3][3] == 0
def test_float_input_agrees_with_fractions():
rng = random.Random(6)
frames = [rand_frame(rng, 3, 3) for _ in range(2)]
shifts = [(F(0), F(0)), (F(3, 10), F(7, 10))]
exact, _ = drizzle(frames, shifts, F(1, 2), F(7, 10), (8, 8))
ff = [[[float(v) for v in row] for row in fr] for fr in frames]
fs = [(float(a), float(b)) for a, b in shifts]
approx, _ = drizzle(ff, fs, 0.5, 0.7, (8, 8))
for ra, rb in zip(exact, approx):
for a, b in zip(ra, rb):
assert abs(float(a) - b) < 1e-12
History
The Hubble Deep Field was imaged in 1995 with the WFPC2 camera, whose wide field pixels were large compared with the PSF of the telescope. The observers took many frames with small offsets. Fruchter and Hook developed drizzle to combine them without the extra blur of interpolation, and described it in their 2002 paper. Drizzle then became part of the standard processing of Hubble images. The idea of shift-and-add, the case , is older and is the basis of many multiframe methods; Farsiu et al. (2004) showed that it is the least squares fit, and its median version the L1 fit, for pure translation.
References
- Andrew S. Fruchter and Richard N. Hook, Drizzle: a method for the linear reconstruction of undersampled images, Publications of the Astronomical Society of the Pacific 114(792), 2002, 144 to 152, the drizzle algorithm (drops, pixfrac, output scale, weights and overlap areas), the conservation of flux and surface brightness, and the correlated noise of the output
- Sina Farsiu, M. Dirk Robinson, Michael Elad and Peyman Milanfar, Fast and robust multiframe super resolution, IEEE Transactions on Image Processing 13(10), 2004, 1327 to 1344, shift-and-add as the least squares and median fits for pure translation
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 GWCHWD Edit this page History Report an error Markdown