Algorithm Search⌘K

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
Properties
deterministichandles bad pixelsnot iterativekeeps fluxlinear
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 KK input frames of the same scene, each with nn pixels. Pixel ii of a frame has the value did_i in counts and a weight wi≥0w_i \ge 0 (an inverse variance, or 00 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 ss, in units of the input pixel side, with s<1s < 1 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.

  1. DRIZZLE(frames, shifts, weights, s, p) ▷ s: output pixel side, p: drop side (pixfrac)
  2. 1W ← 0, V ← 0 on the output grid
  3. 2for each frame k and each input pixel i with value d and weight w > 0
  4. 3drop ← square of side p around the center of pixel i, shifted by shift_k
  5. 4for each output pixel o that the drop overlaps
  6. 5a ← area(drop ∩ o)
  7. 6W_o ← W_o + a·w, V_o ← V_o + a·w·d
  8. 7for each output pixel o
  9. 8I_o ← s² · V_o / W_o if W_o > 0, else 0 ▷ counts per output pixel
  10. 9return I, W

Line L8 turns counts per input pixel into counts per output pixel with the factor s2s^2, the ratio of the pixel areas. The weight image WW 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, A=(2,6,2)A = (2, 6, 2) shifted by 1/41/4 and B=(4,4,0)B = (4, 4, 0) shifted by 3/43/4 along the row. The output pixels have the side s=1/2s = 1/2, so the output has two rows, and the two rows are equal. The drop of pixel jj of AA is centered at j+3/4j + 3/4 and that of BB at j+5/4j + 5/4. One output row (columns 00 to 77, in counts per output pixel) for three pixfracs, computed in exact arithmetic:

pp output II weight WW per column
11 1/2, 2/3, 1, 5/4, 1, 1/2, 1/6, 01/2,\ 2/3,\ 1,\ 5/4,\ 1,\ 1/2,\ 1/6,\ 0 1/8, 3/8, 1/2, 1/2, 1/2, 1/2, 3/8, 1/81/8,\ 3/8,\ 1/2,\ 1/2,\ 1/2,\ 1/2,\ 3/8,\ 1/8
3/43/4 1/2, 3/5, 1, 4/3, 1, 1/2, 1/10, 01/2,\ 3/5,\ 1,\ 4/3,\ 1,\ 1/2,\ 1/10,\ 0 3/64, 15/64, 9/32, 9/32, 9/32, 9/32, 15/64, 3/643/64,\ 15/64,\ 9/32,\ 9/32,\ 9/32,\ 9/32,\ 15/64,\ 3/64
1/21/2 0, 1/2, 1, 3/2, 1, 1/2, 0, 00,\ 1/2,\ 1,\ 3/2,\ 1,\ 1/2,\ 0,\ 0 0, 1/8, 1/8, 1/8, 1/8, 1/8, 1/8, 00,\ 1/8,\ 1/8,\ 1/8,\ 1/8,\ 1/8,\ 1/8,\ 0

With p=1/2p = 1/2 each drop covers exactly one output column. The output is the interlaced sequence A0,B0,A1,B1,A2,B2A_0, B_0, A_1, B_1, A_2, B_2 divided by 44, and the peak 3/23/2 is the sharpest. With p=1p = 1 each drop covers three output pixels, the peak falls to 5/45/4, and the edges of the field get partial coverage. In each case ∑oWoIo=s2p2∑idi\sum_o W_o I_o = s^2 p^2 \sum_i d_i: the totals over both output rows are 9/29/2, 81/3281/32 and 9/89/8 for p=1,3/4,1/2p = 1, 3/4, 1/2, and the input total is 1818.

Correctness

The full proof is in proofs/correctness.md. The facts, all theorems about the computation:

  1. 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.
  2. Weighted mean. Where Wo>0W_o > 0, Io/s2I_o/s^2 is a convex combination of the values of the drops that touch oo. A flat input of cc counts per pixel gives cs2c s^2 counts per output pixel everywhere it is covered: the surface brightness is kept.
  3. Weighted flux. When every drop lies inside the output grid, ∑oWoIo=s2p2∑iwidi\sum_o W_o I_o = s^2p^2\sum_i w_i d_i and ∑oWo=p2∑iwi\sum_o W_o = p^2 \sum_i w_i.
  4. Linearity. For fixed geometry and weights, II is linear in the data.
  5. Special cases. With s=p=1s = p = 1 and integer shifts drizzle is shift-and-add. With s=p=1/2s = p = 1/2 and four dithers at half-pixel offsets, each drop is one output pixel and the result is the interlaced image divided by 44.
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 ii (of any frame) has the value did_i (counts per input pixel), the weight wi≥0w_i \ge 0 and, after the geometric transform, the drop Δi\Delta_i: a square of side pp around the transformed pixel center. Here the transform is a shift, so Δi\Delta_i is an axis-aligned square of area p2p^2. Output pixel oo is the square QoQ_o of side ss. Lines L1 to L8 compute

aio=∣Δi∩Qo∣,Wo=∑iaiowi,Io={s2∑iaiowidiWoWo>0,0Wo=0.a_{io} = |\Delta_i \cap Q_o|, \qquad W_o = \sum_i a_{io} w_i, \qquad I_o = \begin{cases} s^2 \dfrac{\sum_i a_{io} w_i d_i}{W_o} & W_o > 0, \\ 0 & W_o = 0. \end{cases}

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, aio=ℓxℓya_{io} = \ell_x \ell_y, where ℓx\ell_x and ℓy\ell_y are the lengths of the intersections of the projections on the two axes, and ℓ(a0,a1,b0,b1)=max⁡(0,min⁡(a1,b1)−max⁡(a0,b0))\ell(a_0, a_1, b_0, b_1) = \max(0, \min(a_1, b_1) - \max(a_0, b_0)). The loop of line L4 visits every oo with aio>0a_{io} > 0.

Proof. The intersection of two axis-aligned rectangles is the product of the intersections of their sides, which are intervals; the length of [a0,a1]∩[b0,b1][a_0, a_1] \cap [b_0, b_1] is the formula. Output column JJ covers [Js,(J+1)s][Js, (J+1)s], and it meets [x0,x1][x_0, x_1] in a set of positive length only if Js<x1Js < x_1 and (J+1)s>x0(J+1)s > x_0, that is ⌊x0/s⌋≤J≤⌈x1/s⌉−1\lfloor x_0/s \rfloor \le J \le \lceil x_1/s \rceil - 1; the same holds for the rows. □\square

The test compares the areas with a brute force count of lattice cells of side 1/201/20, which is exact when all edges lie on the lattice.

Claim 2 (weighted mean). If Wo>0W_o > 0, Io/s2I_o/s^2 is a convex combination of the values did_i of the drops that overlap QoQ_o with wi>0w_i > 0. In particular, if all such did_i equal cc, then Io=cs2I_o = c s^2.

Proof. The coefficients aiowi/Woa_{io}w_i/W_o are nonnegative and sum to 11. □\square

So a flat input of cc counts per input pixel gives cs2c s^2 counts per output pixel: the surface brightness is kept, for any shifts, any pp and any weights.

Claim 3 (weighted flux). If every drop lies inside the output grid, then

∑oWoIo=s2p2∑iwidi,∑oWo=p2∑iwi.\sum_o W_o I_o = s^2 p^2 \sum_i w_i d_i, \qquad \sum_o W_o = p^2 \sum_i w_i.

Proof. For Wo>0W_o > 0, WoIo=s2∑iaiowidiW_o I_o = s^2 \sum_i a_{io}w_i d_i, and for Wo=0W_o = 0 both sides are 00 because then aiowi=0a_{io}w_i = 0 for all ii. Sum over oo and swap the sums: ∑oaio=∣Δi∣=p2\sum_o a_{io} = |\Delta_i| = p^2, because the output pixels tile the plane and the drop lies inside the grid. The second identity is the same with di=1d_i = 1. □\square

With equal weights, ∑oWoIo/∑oWo=s2⋅\sum_o W_o I_o / \sum_o W_o = s^2 \cdot the mean input value: the flux of the input, measured in counts per output pixel, is kept in the weighted sense. The plain sum ∑oIo\sum_o I_o is the total flux only where the output pixels are covered with a uniform weight.

Claim 4 (linearity). For fixed shifts, pp, ss and weights, II is a linear function of the data dd, and WW does not depend on dd.

Proof. aioa_{io} and wiw_i do not depend on dd, and IoI_o is a fixed linear combination of the did_i. □\square

Claim 5 (shift-and-add). With s=p=1s = p = 1, integer shifts and unit weights, IoI_o is the mean of the input values whose pixels land exactly on QoQ_o.

Proof. A drop of side 11 shifted by integers is exactly one output pixel, so aio∈{0,1}a_{io} \in \{0, 1\} and Io=∑i→odi/#{i→o}I_o = \sum_{i \to o} d_i / \#\{i \to o\}. □\square

Claim 6 (interlacing). Let s=p=1/2s = p = 1/2 and use four frames with the shifts (b/2−1/4+c,a/2−1/4+c)(b/2 - 1/4 + c, a/2 - 1/4 + c) for a,b∈{0,1}a, b \in \{0, 1\} and a fixed cc. Then the drop of pixel (i,j)(i, j) of frame (a,b)(a, b) is exactly one output pixel, and I=14dI = \frac14 d on the interlaced grid.

Proof. The center of the drop is at x=j+1/2+b/2−1/4+cx = j + 1/2 + b/2 - 1/4 + c, so the drop covers [j+b/2+c,j+b/2+c+1/2][j + b/2 + c, j + b/2 + c + 1/2], which is the output column J=2j+b+2cJ = 2j + b + 2c when 2c2c is an integer. The same holds for the rows. So aio=1/4a_{io} = 1/4 for exactly one oo, and Io=s2di=di/4I_o = s^2 d_i = d_i/4. □\square

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 p=1p = 1 the same frames give a smoother output, because each input pixel covers several output pixels. ■\blacksquare

Complexity

In the real-RAM model, each drop overlaps at most c=(⌈p/s⌉+1)2c = (\lceil p/s \rceil + 1)^2 output pixels, and each overlap costs O(1)O(1) for a square. So the KnKn drops cost Θ(Knc)\Theta(Knc), and the final division costs Θ(m)\Theta(m) for mm output pixels: Θ(Knc+m)\Theta(Knc + m) in total, with Θ(m)\Theta(m) extra space for WW and VV. A general transform needs the area of a quadrilateral clipped to a square, still O(1)O(1) 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 00. Then drizzle again.
  • Kernels. Replace the square drop by a point (the limit p→0p \to 0, 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 WW, and raise the pixfrac until WW 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 p>sp > s. Error bars from the pixel to pixel scatter are too small.
  • Units. The output is in counts per output pixel. Forgetting the factor s2s^2 changes every flux by 1/s21/s^2.
  • Edges. The plain sum ∑oIo\sum_o I_o 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.

drizzle.pyI0RawGitHub
# 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 p=s=1p = s = 1, 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

  1. 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
  2. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example