Algorithm Search⌘K

Algorithmadvanced

Multi-band blending

Also called Burt-Adelson blending, Laplacian pyramid blending.

Blend two images by blending each level of their Laplacian pyramids with a mask smoothed to the same level, so low frequencies mix widely and high ones narrowly.

Time
Θ(W H + N) worst · average · best
Space
Θ(W H + N) extra
Where
H = the image height in pixels; N = the number of pyramid levels above the image; W = the image width in pixels
Properties
deterministicexactofflineiterative
Origin
Peter J. Burt, Edward H. Adelson, 1983

Multi-band blending joins two images AA and BB along a mask MM, which is 1 where the result should come from AA and 0 where it should come from BB. It splits both images into frequency bands with a Laplacian pyramid, mixes each band with the mask blurred to the same scale by a Gaussian pyramid, and adds the mixed bands back. Coarse bands thus cross the seam over a wide zone and fine bands over a narrow one, so the seam shows neither as a step nor as a ghosted double edge. Plain alpha blending mixes all frequencies with one weight map; Poisson image editing mixes gradients and solves a linear system. This page gives the algorithm for two images; the whole task of making a panorama is image stitching.

In plain words

When you put two photos side by side, a hard cut shows a line where the brightness jumps. If you instead fade one photo into the other over a wide strip, small details from both photos show at the same time, and edges look doubled. Multi-band blending avoids both faults. It splits each photo into layers, from broad shading to fine detail. Broad shading is faded over a wide strip, so there is no visible jump in brightness. Fine detail is faded over a narrow strip, so each detail comes almost only from one photo and nothing looks doubled. At the end, the faded layers are added back into one picture. The width of each strip follows the size of the features in its layer.

The problem

Input. Two images AA and BB of size W×HW \times H with real pixel values, a mask MM of the same size with values in [0,1][0, 1], and a number of levels N≥0N \ge 0. For a color image, run the algorithm on each channel.

Output. The image SS obtained by collapsing the pyramid of mixed bands

LlS=GlM⊙LlA+(1−GlM)⊙LlB,l=0,…,N,L^S_l = G^M_l \odot L^A_l + (1 - G^M_l) \odot L^B_l, \qquad l = 0, \ldots, N,

where GMG^M is the Gaussian pyramid of MM, LAL^A and LBL^B are the Laplacian pyramids of AA and BB, and ⊙\odot is the product sample by sample. REDUCE and EXPAND are those of the Laplacian pyramid page: the 5-tap kernel 116(1,4,6,4,1)\frac{1}{16}(1, 4, 6, 4, 1), the reflect-101 border, level sizes ⌈Wl/2⌉×⌈Hl/2⌉\lceil W_l / 2 \rceil \times \lceil H_l / 2 \rceil, and EXPAND by zero insertion and a blur with gain 2 per axis.

The algorithm

  1. MULTI-BAND-BLEND(A, B, M, N)
  2. 1G^M <- the Gaussian pyramid of M with levels 0 .. N
  3. 2G^A, G^B <- the Gaussian pyramids of A and B with levels 0 .. N
  4. 3L^A, L^B <- the Laplacian pyramids: L_l = G_l - EXPAND(G_(l+1)) for l < N, and L_N = G_N
  5. 4for l <- 0 to N
  6. 5L^S_l <- G^M_l * L^A_l + (1 - G^M_l) * L^B_l, sample by sample
  7. 6S <- L^S_N
  8. 7for l <- N - 1 down to 0
  9. 8S <- L^S_l + EXPAND(S) to the size of level l
  10. 9return S

Line L1 smooths the mask more at each level, so the weight at level ll changes over a zone about 2l2^l pixels wide in the original image. Lines L2 and L3 build the bands of both images. Line L5 is a plain alpha blend of one band with the matching mask level. Lines L6 to L8 are the reconstruction of the Laplacian pyramid, applied to the mixed bands. At level 0 the mask is not smoothed at all, so the finest detail switches from AA to BB at the seam of MM; the top level NN holds the mean brightness and mixes it with the most smoothed mask.

Example

One row of 8 pixels: A=(16,16,16,16,16,16,16,16)A = (16, 16, 16, 16, 16, 16, 16, 16), B=(0,0,0,0,0,0,0,0)B = (0, 0, 0, 0, 0, 0, 0, 0) and M=(1,1,1,1,0,0,0,0)M = (1, 1, 1, 1, 0, 0, 0, 0), with N=1N = 1. The height is 1, so only the horizontal axis is filtered.

line value
L1 G0M=(1,1,1,1,0,0,0,0)G^M_0 = (1, 1, 1, 1, 0, 0, 0, 0), G1M=(1,1516,516,0)G^M_1 = (1, \frac{15}{16}, \frac{5}{16}, 0)
L2 G0A=16G^A_0 = 16 at all 8 samples, G1A=(16,16,16,16)G^A_1 = (16, 16, 16, 16); GBG^B is 0
L3 L0A=0L^A_0 = 0 at all 8 samples, L1A=(16,16,16,16)L^A_1 = (16, 16, 16, 16); LBL^B is 0
L4, L5 L0S=0L^S_0 = 0 at all 8 samples, L1S=(16,15,5,0)L^S_1 = (16, 15, 5, 0)
L6 S=(16,15,5,0)S = (16, 15, 5, 0)
L7, L8 S=0+EXPAND(16,15,5,0)=(634,312,1118,10,458,52,58,0)S = 0 + \mathrm{EXPAND}(16, 15, 5, 0) = (\frac{63}{4}, \frac{31}{2}, \frac{111}{8}, 10, \frac{45}{8}, \frac{5}{2}, \frac{5}{8}, 0)
L9 return SS

Two values in detail. In line L1, the second sample of G1MG^M_1 is centered on pixel 2 and reads pixels 0 to 4, so it is (1+4+6+4+0)/16=15/16(1 + 4 + 6 + 4 + 0)/16 = 15/16. In line L8, the zero-inserted row is (16,0,15,0,5,0,0,0)(16, 0, 15, 0, 5, 0, 0, 0); at x=0x = 0 the taps read pixels 2,1,0,1,22, 1, 0, 1, 2 after the border, with values 15,0,16,0,1515, 0, 16, 0, 15, so the first output is 2⋅(15+6⋅16+15)/16=63/42 \cdot (15 + 6 \cdot 16 + 15)/16 = 63/4.

With N=0N = 0 the result is the hard cut (16,16,16,16,0,0,0,0)(16, 16, 16, 16, 0, 0, 0, 0). With N=1N = 1 the step of 16 is spread over about 7 pixels. With N=3N = 3 the top level is one pixel wide, and the result is the constant 337/32337/32 at every pixel: the whole image is a single band, mixed with the single weight 337/512337/512. Too many levels for the size of the overlap remove the seam and also the difference between the two sides.

Correctness

The specification is the formula in the problem statement. Lines L1 to L5 compute the mixed bands LlSL^S_l by definition, and lines L6 to L8 are the reconstruction of a Laplacian pyramid applied to them, so S=∑l=0NEXPAND(l)(LlS)S = \sum_{l=0}^{N} \mathrm{EXPAND}^{(l)}(L^S_l), where EXPAND(l)\mathrm{EXPAND}^{(l)} expands from level ll to level 0 step by step. Because REDUCE and EXPAND are linear and collapse inverts the Laplacian pyramid exactly, the result has the properties a blend should have. If M=1M = 1 everywhere, S=AS = A; if M=0M = 0, S=BS = B; if A=BA = B, S=AS = A for every mask. If MM is a constant cc, then S=cA+(1−c)BS = cA + (1 - c)B, since REDUCE keeps constants. With N=0N = 0 the algorithm is the plain blend M⊙A+(1−M)⊙BM \odot A + (1 - M) \odot B. Each level of GMG^M lies in [0,1][0, 1], because REDUCE takes weighted means with non-negative weights, so each band is a convex mix of the two input bands. The full proof is below.

Proof: Multi-band blending collapses the mixed bands exactly and reproduces the trivial blendsfull

We use the notation of the page. The images AA, BB and the mask MM have size W×HW \times H, with W,H≥1W, H \ge 1, and N≥0N \ge 0. Level ll has size Wl×HlW_l \times H_l with W0=WW_0 = W, H0=HH_0 = H, Wl+1=⌈Wl/2⌉W_{l+1} = \lceil W_l / 2 \rceil and Hl+1=⌈Hl/2⌉H_{l+1} = \lceil H_l / 2 \rceil. An image of size w×hw \times h is an h×wh \times w matrix. Let w^=116(1,4,6,4,1)\hat w = \frac{1}{16}(1, 4, 6, 4, 1), indexed by k=−2,…,2k = -2, \ldots, 2, and let ρn(i)\rho_n(i) be the reflect-101 index of ii in 0,…,n−10, \ldots, n - 1 (with ρ1(i)=0\rho_1(i) = 0).

For n≥1n \ge 1 and m=⌈n/2⌉m = \lceil n / 2 \rceil, define the m×nm \times n matrix RnR_n and the n×mn \times m matrix EnE_n by

(Rn)i,a=∑k:ρn(2i+k)=aw^(k),(En)x,j=γn∑k:ρn(x−k)=2jw^(k),(R_n)_{i, a} = \sum_{k : \rho_n(2i + k) = a} \hat w(k), \qquad (E_n)_{x, j} = \gamma_n \sum_{k : \rho_n(x - k) = 2j} \hat w(k),

with γn=2\gamma_n = 2 for n>1n > 1 and γ1=1\gamma_1 = 1. The code computes REDUCE(g)=Rh g RwT\mathrm{REDUCE}(g) = R_{h} \, g \, R_{w}^{\mathsf T} for gg of size w×hw \times h, since it filters each row with the taps w^(k)\hat w(k) at ρw(2i+k)\rho_w(2i + k) and then each column in the same way. It computes EXPAND(g)\mathrm{EXPAND}(g) to size w×hw \times h as Eh g EwTE_{h} \, g \, E_{w}^{\mathsf T}, since the zero-inserted grid is nonzero only at even indices 2j2j, and the filter with gain γ\gamma reads w^(k)\hat w(k) times the value at ρ(x−k)\rho(x - k).

Claim. Let SS be the output of MULTI-BAND-BLEND(A,B,M,N)(A, B, M, N), and let LlSL^S_l be the bands of line L5.

(a) S=C(L0S,…,LNS)S = C(L^S_0, \ldots, L^S_N), where the collapse CC is defined by SN=LNSS_N = L^S_N and Sl=LlS+EXPAND(Sl+1)S_l = L^S_l + \mathrm{EXPAND}(S_{l+1}) to the size of level ll, and C(…)=S0C(\ldots) = S_0.

(b) If MM is the constant cc, then S=cA+(1−c)BS = cA + (1 - c)B. In particular M=1M = 1 gives S=AS = A and M=0M = 0 gives S=BS = B.

(c) If A=BA = B, then S=AS = A for every mask MM.

(d) If N=0N = 0, then S=M⊙A+(1−M)⊙BS = M \odot A + (1 - M) \odot B.

(e) If every entry of MM is in [0,1][0, 1], then every entry of every level GlMG^M_l is in [0,1][0, 1], so each sample of LlSL^S_l is a convex combination of the matching samples of LlAL^A_l and LlBL^B_l.

(f) For a fixed mask, SS is a linear function of the pair (A,B)(A, B).

Lemma 1 (REDUCE takes weighted means). Every entry of RnR_n is non-negative, and every row of RnR_n sums to 1. So REDUCE is linear, maps the constant image cc to the constant image cc, and maps an image with all entries in [0,1][0, 1] to an image with all entries in [0,1][0, 1]. EXPAND is linear.

Proof. Row ii of RnR_n collects the five weights w^(−2),…,w^(2)\hat w(-2), \ldots, \hat w(2), each added to the column ρn(2i+k)\rho_n(2i + k). The map ρn\rho_n only decides into which column a weight goes; two weights may go to the same column, but none is lost and none is negative. So the row has non-negative entries with sum ∑kw^(k)=16/16=1\sum_k \hat w(k) = 16/16 = 1. This also holds for n=1n = 1, where all five weights go to column 0.

An entry of REDUCE(g)\mathrm{REDUCE}(g) is ∑a,b(Rh)j,a(Rw)i,b ga,b\sum_{a, b} (R_h)_{j, a} (R_w)_{i, b} \, g_{a, b}. The coefficients (Rh)j,a(Rw)i,b(R_h)_{j, a} (R_w)_{i, b} are non-negative and sum to (∑a(Rh)j,a)(∑b(Rw)i,b)=1\big(\sum_a (R_h)_{j, a}\big)\big(\sum_b (R_w)_{i, b}\big) = 1. So each entry is a weighted mean of the entries of gg: it equals cc when gg is the constant cc, and it lies between the least and the largest entry of gg, hence in [0,1][0, 1] when gg has entries in [0,1][0, 1]. Both REDUCE and EXPAND are products with fixed matrices on each side, so both are linear. □\square

Lemma 2 (the pyramids are linear). For images XX, YY and reals α\alpha, β\beta, the Gaussian and Laplacian pyramids satisfy GlαX+βY=αGlX+βGlYG^{\alpha X + \beta Y}_l = \alpha G^X_l + \beta G^Y_l and LlαX+βY=αLlX+βLlYL^{\alpha X + \beta Y}_l = \alpha L^X_l + \beta L^Y_l for l=0,…,Nl = 0, \ldots, N.

Proof. For the Gaussian pyramid, use induction on ll. Level 0 is the image itself. If the statement holds at level ll, then level l+1l + 1 is REDUCE(αGlX+βGlY)=αGl+1X+βGl+1Y\mathrm{REDUCE}(\alpha G^X_l + \beta G^Y_l) = \alpha G^X_{l+1} + \beta G^Y_{l+1} by Lemma 1. For l<Nl < N, Ll=Gl−EXPAND(Gl+1)L_l = G_l - \mathrm{EXPAND}(G_{l+1}) is a linear expression in the Gaussian levels, with EXPAND linear by Lemma 1, and LN=GNL_N = G_N. □\square

Lemma 3 (collapse inverts the Laplacian pyramid). For every image XX of size W×HW \times H, C(L0X,…,LNX)=XC(L^X_0, \ldots, L^X_N) = X.

Proof. Let SlS_l be the intermediate values of the collapse. We show Sl=GlXS_l = G^X_l by downward induction on ll. For l=Nl = N, SN=LNX=GNXS_N = L^X_N = G^X_N. If Sl+1=Gl+1XS_{l+1} = G^X_{l+1}, then

Sl=LlX+EXPAND(Sl+1)=(GlX−EXPAND(Gl+1X))+EXPAND(Gl+1X)=GlX.S_l = L^X_l + \mathrm{EXPAND}(S_{l+1}) = \big(G^X_l - \mathrm{EXPAND}(G^X_{l+1})\big) + \mathrm{EXPAND}(G^X_{l+1}) = G^X_l .

Here both EXPAND terms are computed from the same array to the same size Wl×HlW_l \times H_l, so they are equal and cancel. At l=0l = 0 this gives S0=G0X=XS_0 = G^X_0 = X. □\square

The proof uses only that the same EXPAND appears in the build and in the collapse; with exact arithmetic (integers or fractions, as in the code) the cancellation is exact.

Lemma 4 (the collapse is linear). CC is a linear function of its N+1N + 1 arguments, and C(Λ0,…,ΛN)=∑l=0NEXPAND(l)(Λl)C(\Lambda_0, \ldots, \Lambda_N) = \sum_{l=0}^{N} \mathrm{EXPAND}^{(l)}(\Lambda_l), where EXPAND(0)\mathrm{EXPAND}^{(0)} is the identity and EXPAND(l)\mathrm{EXPAND}^{(l)} expands from level ll to level l−1l - 1, then to level l−2l - 2, and so on down to level 0.

Proof. By downward induction, Sl=∑k=lNEXPAND(k→l)(Λk)S_l = \sum_{k=l}^{N} \mathrm{EXPAND}^{(k \to l)}(\Lambda_k), where EXPAND(k→l)\mathrm{EXPAND}^{(k \to l)} expands step by step from level kk to level ll. This holds at l=Nl = N, and if it holds at l+1l + 1, then Sl=Λl+EXPAND(Sl+1)=Λl+∑k=l+1NEXPAND(k→l)(Λk)S_l = \Lambda_l + \mathrm{EXPAND}(S_{l+1}) = \Lambda_l + \sum_{k=l+1}^{N} \mathrm{EXPAND}^{(k \to l)}(\Lambda_k) by the linearity of EXPAND (Lemma 1). Take l=0l = 0. A sum of linear maps is linear. □\square

Proof of the claim.

(a) Lines L1 to L3 compute GMG^M, GAG^A, GBG^B, LAL^A and LBL^B as defined; in the code, laplacian_from_gaussian forms Ll=Gl−EXPAND(Gl+1)L_l = G_l - \mathrm{EXPAND}(G_{l+1}) for l<Nl < N and keeps LN=GNL_N = G_N. The loop L4 and L5 runs for l=0,…,Nl = 0, \ldots, N and stores LlSL^S_l. Line L6 sets S=LNS=SNS = L^S_N = S_N. The loop L7 and L8 runs for l=N−1l = N - 1 down to 0. Before the pass for level ll the variable holds Sl+1S_{l+1}, and line L8 replaces it by LlS+EXPAND(Sl+1)=SlL^S_l + \mathrm{EXPAND}(S_{l+1}) = S_l. After the pass for l=0l = 0, line L9 returns S0=C(L0S,…,LNS)S_0 = C(L^S_0, \ldots, L^S_N). If N=0N = 0 the loop does not run and the output is L0S=S0L^S_0 = S_0.

(b) Let MM be the constant cc. By Lemma 1 and induction on ll, every level GlMG^M_l is the constant cc. So line L5 gives LlS=cLlA+(1−c)LlBL^S_l = c L^A_l + (1 - c) L^B_l, which is LlcA+(1−c)BL^{cA + (1 - c)B}_l by Lemma 2. By (a) and Lemma 3, S=C(LcA+(1−c)B)=cA+(1−c)BS = C(L^{cA + (1 - c)B}) = cA + (1 - c)B. For c=1c = 1 this is AA, and for c=0c = 0 it is BB.

(c) If A=BA = B, then LlA=LlBL^A_l = L^B_l and line L5 gives LlS=GlM⊙LlA+(1−GlM)⊙LlA=LlAL^S_l = G^M_l \odot L^A_l + (1 - G^M_l) \odot L^A_l = L^A_l, whatever GlMG^M_l is. By (a) and Lemma 3, S=AS = A.

(d) If N=0N = 0, then G0M=MG^M_0 = M and L0A=G0A=AL^A_0 = G^A_0 = A, L0B=BL^B_0 = B. So L0S=M⊙A+(1−M)⊙BL^S_0 = M \odot A + (1 - M) \odot B, and by (a) the output is L0SL^S_0.

(e) G0M=MG^M_0 = M has entries in [0,1][0, 1], and each next level is REDUCE of the previous one, so by Lemma 1 and induction every level has entries in [0,1][0, 1]. A sample of LlSL^S_l is ga+(1−g)bg a + (1 - g) b with g∈[0,1]g \in [0, 1], a convex combination of aa and bb.

(f) For a fixed MM the levels GlMG^M_l are fixed. The map (A,B)↦(LlA,LlB)(A, B) \mapsto (L^A_l, L^B_l) is linear by Lemma 2, line L5 is linear in (LlA,LlB)(L^A_l, L^B_l) for fixed weights, and CC is linear by Lemma 4. A composition of linear maps is linear. ■\blacksquare

Remark (the result is not a convex mix of pixels). Part (e) holds for each band, but not for the collapsed image. The bands LlL_l for l<Nl < N take both signs, and the sum of Lemma 4 adds the mixed bands without any check on the range. For A=(0,0,0,0,16,16,16,16)A = (0, 0, 0, 0, 16, 16, 16, 16), B=16B = 16 everywhere, M=(1,1,1,1,1,1,0,0)M = (1, 1, 1, 1, 1, 1, 0, 0), one row, and N=1N = 1, the fifth output pixel is 1039/64>161039/64 > 16, larger than every input pixel. The test file checks this value.

Remark (termination and cost). The loops run N+1N + 1 and NN times, and each REDUCE, EXPAND or mix touches each sample of its level a fixed number of times, which gives the bound Θ(WH+N)\Theta(W H + N) of the page.

Complexity

Level ll has ⌈W/2l⌉⋅⌈H/2l⌉≤(W/2l+1)(H/2l+1)\lceil W / 2^l \rceil \cdot \lceil H / 2^l \rceil \le (W / 2^l + 1)(H / 2^l + 1) samples, and each sample of REDUCE or EXPAND reads 5 values per axis. Summed over the levels, each pyramid has at most 43WH+2(W+H)+N+1\frac{4}{3} W H + 2(W + H) + N + 1 samples, so the time and the extra space are Θ(WH+N)\Theta(W H + N) in the real RAM model. The term NN counts levels that are already 1×11 \times 1; in practice N≤log⁡2max⁡(W,H)N \le \log_2 \max(W, H), and the cost is Θ(WH)\Theta(W H). With integer or rational pixels every step is exact. In floating point the result has the small rounding errors of a few dozen additions and products per pixel.

Properties

  • Exact on trivial masks. M=1M = 1 gives AA, M=0M = 0 gives BB, and A=BA = B gives AA, for any NN.
  • Linear in the images. For a fixed mask, SS is a linear function of (A,B)(A, B). It is not linear in MM jointly with the images.
  • Not a convex mix of pixels. The bands are mixed with weights in [0,1][0, 1], but the collapsed result can leave the range of the inputs. For A=(0,0,0,0,16,16,16,16)A = (0, 0, 0, 0, 16, 16, 16, 16), B=16B = 16 everywhere, M=(1,1,1,1,1,1,0,0)M = (1, 1, 1, 1, 1, 1, 0, 0) and N=1N = 1, the fifth pixel is 1039/64≈16.23>161039/64 \approx 16.23 > 16. Clamp the result to the valid range.
  • Local. A change of AA, BB or MM at one pixel changes SS only within about 2N+22^{N+2} pixels of it, since each level has a filter of 5 taps.
  • Deterministic and not iterative. It builds three pyramids and collapses one, with no system to solve.

Variants and improvements

  • Many images. Give each image IkI_k a weight map MkM_k, with ∑kMk=1\sum_k M_k = 1 at each pixel. Then the mixed band is ∑kGlMk⊙LlIk\sum_k G^{M_k}_l \odot L^{I_k}_l. Because REDUCE is linear and keeps constants, the levels GlMkG^{M_k}_l also sum to 1. If the maps do not sum to 1, divide each mixed band by ∑kGlMk\sum_k G^{M_k}_l.
  • Brown and Lowe. For a panorama, each pixel of the output is given to the image whose weight, largest at its center, is the highest there. The resulting max-weight maps are the masks. Brown and Lowe form the bands with Gaussian blurs instead of a decimated pyramid: the first band is I−I∗gσI - I * g_\sigma, and the next bands use blurs of width σ′=2k+1 σ\sigma' = \sqrt{2k + 1}\,\sigma. Their Figure 7 uses 5 bands and σ=5\sigma = 5 pixels.
  • Feathering. Mix all frequencies with one smooth weight map, for example from a distance transform of each image's border. It is one pass, but it gives ghosts when the images are not perfectly aligned.
  • Gradient domain blending. Poisson image editing keeps the gradients of each image and solves for pixel values. It removes exposure differences that a pyramid spreads only over its widest zone, at the cost of solving a large sparse system.
  • Seams first. Choose the seam where the images agree, for example by a minimum cut, and then blend along it with a few levels.

When to use it

Use it to hide the seams of a panorama or a photo montage after the images are aligned and their exposures are roughly matched. It is fast, simple and robust to small alignment errors, since fine detail switches quickly between the images. It does not fix a large exposure difference, parallax or a moving object; for those, compensate the gains first, place the seam with care, or use a gradient domain method.

Pitfalls

  • Too many levels. If the top level is smaller than the overlap, the lowest band mixes content from far away, and the mean brightness of one image leaks across the whole result. Stop the pyramid when the top level is about as large as the overlap.
  • Seam outside the overlap. At level 0 the mask is used as it is, and the coarser levels spread it over a wide zone around the seam. Put the seam well inside the overlap, so that this zone has valid pixels of both images.
  • Invalid pixels in the pyramid. Black borders of a warped image enter the coarse levels of its pyramid. Fill them first, for example by extending the image, or use weights normalized by the blurred valid mask.
  • Overshoot. The result can leave the valid range; clamp it.
  • Different sizes. AA, BB and MM must have the same size, and REDUCE and EXPAND must use the same rounding of sizes at every level, or the bands do not line up.

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.

multi_band_blending.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/multi-band-blending/. The authors are listed in prov/AXXSRR.jsonl.
"""Multi-band blending of two images with a mask (Burt and Adelson, 1983).

An image is a list of rows; pixel (u, v) is img[v][u]. A, B and the mask M
have the same size W x H; M holds weights in [0, 1], 1 where the result
should come from A. Each image is split into a Laplacian pyramid, each band
is mixed with the matching level of the Gaussian pyramid of M, and the
mixed pyramid is collapsed.

REDUCE and EXPAND follow the Laplacian pyramid page: the 5-tap binomial
kernel (1, 4, 6, 4, 1) / 16, the reflect-101 border, sizes ceil(W / 2) and
ceil(H / 2), and EXPAND by zero insertion and a blur with twice the kernel.
With int or Fraction pixels every step is exact.

Cost: O(W H) time and space for any number of levels, because the levels
shrink by a factor of 4.
"""

from __future__ import annotations

from fractions import Fraction
from typing import List, Sequence

Image = List[List]
KERNEL = [Fraction(1, 16), Fraction(4, 16), Fraction(6, 16), Fraction(4, 16), Fraction(1, 16)]


def reflect101(i: int, n: int) -> int:
    """Mirror an index into 0 .. n - 1 without repeating the edge sample."""
    if n == 1:
        return 0
    period = 2 * n - 2
    i %= period
    return period - i if i >= n else i


def reduce_level(g: Sequence[Sequence]) -> Image:
    """Blur with the kernel in both directions and keep even rows and columns."""
    h, w = len(g), len(g[0])
    w2, h2 = (w + 1) // 2, (h + 1) // 2
    rows = [[sum(KERNEL[m + 2] * r[reflect101(2 * i + m, w)] for m in range(-2, 3))
             for i in range(w2)] for r in g]
    return [[sum(KERNEL[m + 2] * rows[reflect101(2 * j + m, h)][i] for m in range(-2, 3))
             for i in range(w2)] for j in range(h2)]


def expand(g: Sequence[Sequence], width: int, height: int) -> Image:
    """Put g on the even positions of a zero grid of size width x height and
    blur with twice the kernel per axis (once on an axis of length 1)."""
    z = [[0] * width for _ in range(height)]
    for j, row in enumerate(g):
        for i, val in enumerate(row):
            z[2 * j][2 * i] = val
    gx = 1 if width == 1 else 2
    gy = 1 if height == 1 else 2
    r = [[sum(gx * KERNEL[m + 2] * zr[reflect101(x - m, width)] for m in range(-2, 3))
          for x in range(width)] for zr in z]
    return [[sum(gy * KERNEL[m + 2] * r[reflect101(y - m, height)][x] for m in range(-2, 3))
             for x in range(width)] for y in range(height)]


def gaussian_pyramid(img: Sequence[Sequence], levels: int) -> List[Image]:
    """[G_0, ..., G_N] with G_0 = img and G_(l+1) = REDUCE(G_l), N = levels."""
    pyr = [[list(r) for r in img]]
    for _ in range(levels):
        pyr.append(reduce_level(pyr[-1]))
    return pyr


def laplacian_from_gaussian(gp: Sequence[Image]) -> List[Image]:
    """L_l = G_l - EXPAND(G_(l+1)) for l < N, and L_N = G_N."""
    lap = []
    for lvl in range(len(gp) - 1):
        fine = gp[lvl]
        e = expand(gp[lvl + 1], len(fine[0]), len(fine))
        lap.append([[a - b for a, b in zip(rf, re)] for rf, re in zip(fine, e)])
    lap.append([list(r) for r in gp[-1]])
    return lap


def collapse(lap: Sequence[Image]) -> Image:
    """Undo laplacian_from_gaussian: S = L_N, then S = L_l + EXPAND(S)."""
    s = [list(r) for r in lap[-1]]
    for lvl in range(len(lap) - 2, -1, -1):
        band = lap[lvl]
        e = expand(s, len(band[0]), len(band))
        s = [[a + b for a, b in zip(rb, re)] for rb, re in zip(band, e)]
    return s


def multi_band_blend(A: Sequence[Sequence], B: Sequence[Sequence],
                     M: Sequence[Sequence], levels: int) -> Image:
    """Blend A and B with the mask M over levels + 1 frequency bands.

    Precondition: A, B and M are W x H with W, H >= 1, levels >= 0, and the
    entries of M lie in [0, 1]. levels = 0 gives the plain per-pixel mix
    M A + (1 - M) B. Cost O(W H)."""
    if levels < 0:
        raise ValueError("levels must be >= 0")
    h, w = len(A), len(A[0])
    for img in (B, M):
        if len(img) != h or any(len(r) != w for r in img):
            raise ValueError("A, B and M must have the same size")
    gm = gaussian_pyramid(M, levels)  # @line L1
    ga = gaussian_pyramid(A, levels)  # @line L2
    gb = gaussian_pyramid(B, levels)  # @line L2
    la = laplacian_from_gaussian(ga)  # @line L3
    lb = laplacian_from_gaussian(gb)  # @line L3
    ls = []
    for lvl in range(levels + 1):  # @line L4
        ls.append([[m * a + (1 - m) * b for m, a, b in zip(rm, ra, rb)]  # @line L5
                   for rm, ra, rb in zip(gm[lvl], la[lvl], lb[lvl])])
    s = ls[levels]  # @line L6
    for lvl in range(levels - 1, -1, -1):  # @line L7
        band = ls[lvl]
        e = expand(s, len(band[0]), len(band))
        s = [[a + b for a, b in zip(rb, re)] for rb, re in zip(band, e)]  # @line L8
    return s  # @line L9
test_multi_band_blending.py 181 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/multi-band-blending/. The authors are listed in prov/AXXSRR.jsonl.
"""Tests of multi-band blending."""

import random
from fractions import Fraction

import pytest

from multi_band_blending import (collapse, gaussian_pyramid, laplacian_from_gaussian,
                                 multi_band_blend, reflect101)

W5 = [Fraction(c, 16) for c in (1, 4, 6, 4, 1)]


def mirror(i, n):
    """Reflect-101 index, written apart from the module as a fold loop."""
    if n == 1:
        return 0
    while i < 0 or i >= n:
        i = -i if i < 0 else 2 * (n - 1) - i
    return i


def reduce_matrix(n):
    """The ceil(n/2) x n matrix of 1D REDUCE."""
    m = (n + 1) // 2
    r = [[Fraction(0)] * n for _ in range(m)]
    for i in range(m):
        for k in range(-2, 3):
            r[i][mirror(2 * i + k, n)] += W5[k + 2]
    return r


def expand_matrix(n):
    """The n x ceil(n/2) matrix of 1D EXPAND to length n."""
    m = (n + 1) // 2
    gain = 1 if n == 1 else 2
    e = [[Fraction(0)] * m for _ in range(n)]
    for x in range(n):
        for k in range(-2, 3):
            j = mirror(x - k, n)
            if j % 2 == 0:
                e[x][j // 2] += gain * W5[k + 2]
    return e


def matmul(a, b):
    return [[sum(x * y for x, y in zip(row, col)) for col in zip(*b)] for row in a]


def tr(a):
    return [list(c) for c in zip(*a)]


def oracle(A, B, M, levels):
    """Blend by explicit operator matrices: REDUCE(g) = R_h g R_w^T and
    EXPAND(g) = E_h g E_w^T."""
    h, w = len(A), len(A[0])
    sizes = [(h, w)]
    for _ in range(levels):
        sizes.append(((sizes[-1][0] + 1) // 2, (sizes[-1][1] + 1) // 2))

    def red(g, l):
        hh, ww = sizes[l]
        return matmul(matmul(reduce_matrix(hh), g), tr(reduce_matrix(ww)))

    def exp(g, l):
        hh, ww = sizes[l]
        return matmul(matmul(expand_matrix(hh), g), tr(expand_matrix(ww)))

    def gp(img):
        out = [img]
        for l in range(levels):
            out.append(red(out[-1], l))
        return out

    gm, ga, gb = gp(M), gp(A), gp(B)
    bands = []
    for l in range(levels + 1):
        if l < levels:
            ea, eb = exp(ga[l + 1], l), exp(gb[l + 1], l)
            la = [[x - y for x, y in zip(r1, r2)] for r1, r2 in zip(ga[l], ea)]
            lb = [[x - y for x, y in zip(r1, r2)] for r1, r2 in zip(gb[l], eb)]
        else:
            la, lb = ga[l], gb[l]
        bands.append([[m * a + (1 - m) * b for m, a, b in zip(rm, ra, rb)]
                      for rm, ra, rb in zip(gm[l], la, lb)])
    s = bands[-1]
    for l in range(levels - 1, -1, -1):
        e = exp(s, l)
        s = [[x + y for x, y in zip(r1, r2)] for r1, r2 in zip(bands[l], e)]
    return s


def rand_image(rng, h, w, lo=0, hi=255):
    return [[rng.randint(lo, hi) for _ in range(w)] for _ in range(h)]


def rand_mask(rng, h, w):
    return [[Fraction(rng.randint(0, 8), 8) for _ in range(w)] for _ in range(h)]


def test_reflect101():
    for n in range(1, 7):
        for i in range(-12, 18):
            assert reflect101(i, n) == mirror(i, n)


def test_worked_example():
    A, B = [[16] * 8], [[0] * 8]
    M = [[1, 1, 1, 1, 0, 0, 0, 0]]
    assert multi_band_blend(A, B, M, 0) == [[16, 16, 16, 16, 0, 0, 0, 0]]
    want = [Fraction(63, 4), Fraction(31, 2), Fraction(111, 8), 10,
            Fraction(45, 8), Fraction(5, 2), Fraction(5, 8), 0]
    assert multi_band_blend(A, B, M, 1) == [want]
    assert gaussian_pyramid(M, 3)[1] == [[1, Fraction(15, 16), Fraction(5, 16), 0]]
    assert multi_band_blend(A, B, M, 3) == [[Fraction(337, 32)] * 8]


def test_overshoot_example():
    A = [[0, 0, 0, 0, 16, 16, 16, 16]]
    B = [[16] * 8]
    M = [[1, 1, 1, 1, 1, 1, 0, 0]]
    s = multi_band_blend(A, B, M, 1)[0]
    assert max(s) == Fraction(1039, 64)


def test_against_operator_oracle():
    rng = random.Random(1)
    for _ in range(60):
        h, w = rng.randint(1, 7), rng.randint(1, 7)
        levels = rng.randint(0, 3)
        A, B, M = rand_image(rng, h, w), rand_image(rng, h, w), rand_mask(rng, h, w)
        assert multi_band_blend(A, B, M, levels) == oracle(A, B, M, levels)


def test_special_masks_and_equal_images():
    rng = random.Random(2)
    for _ in range(40):
        h, w = rng.randint(1, 9), rng.randint(1, 9)
        levels = rng.randint(0, 4)
        A, B = rand_image(rng, h, w), rand_image(rng, h, w)
        ones = [[1] * w for _ in range(h)]
        zero = [[0] * w for _ in range(h)]
        assert multi_band_blend(A, B, ones, levels) == A
        assert multi_band_blend(A, B, zero, levels) == B
        assert multi_band_blend(A, A, rand_mask(rng, h, w), levels) == A
        c = Fraction(rng.randint(0, 8), 8)
        const = [[c] * w for _ in range(h)]
        want = [[c * a + (1 - c) * b for a, b in zip(ra, rb)] for ra, rb in zip(A, B)]
        assert multi_band_blend(A, B, const, levels) == want


def test_collapse_inverts_the_pyramid():
    rng = random.Random(3)
    for _ in range(30):
        h, w = rng.randint(1, 10), rng.randint(1, 10)
        img = rand_image(rng, h, w)
        assert collapse(laplacian_from_gaussian(gaussian_pyramid(img, rng.randint(0, 4)))) == img


def test_mask_pyramid_stays_in_unit_interval():
    rng = random.Random(4)
    for _ in range(30):
        h, w = rng.randint(1, 10), rng.randint(1, 10)
        for level in gaussian_pyramid(rand_mask(rng, h, w), 4):
            assert all(0 <= x <= 1 for row in level for x in row)


def test_floats_and_bad_input():
    rng = random.Random(5)
    A = [[rng.random() for _ in range(6)] for _ in range(5)]
    B = [[rng.random() for _ in range(6)] for _ in range(5)]
    M = [[1.0 if u < 3 else 0.0 for u in range(6)] for _ in range(5)]
    s = multi_band_blend(A, B, M, 2)
    assert len(s) == 5 and len(s[0]) == 6
    with pytest.raises(ValueError):
        multi_band_blend(A, B, M, -1)
    with pytest.raises(ValueError):
        multi_band_blend(A, B[:4], M, 1)

History

Burt and Adelson (1983) introduced the Laplacian pyramid as an image code and, in the same year, the multiresolution spline for joining images into mosaics: each band is joined over a transition zone that matches its scale. Their paper extended the method from a straight seam to regions of any shape through the Gaussian pyramid of a mask. Brown and Lowe (2007) used multi-band blending as the last step of their automatic panorama stitcher, with one weight map per image.

References

  1. Peter J. Burt and Edward H. Adelson, A multiresolution spline with application to image mosaics, ACM Transactions on Graphics 2(4), 1983, 217-236, the multiresolution spline (each Laplacian level of the result mixes the levels of the two images, with weights from the Gaussian pyramid of the region mask)
  2. Matthew Brown and David G. Lowe, Automatic panoramic image stitching using invariant features, International Journal of Computer Vision 74(1), 2007, 59-73, Section 7, Multi-band blending (max-weight maps, bands of width sigma, sqrt(2k+1) sigma for the next bands, and the normalized sum over images); Figure 7

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