Algorithm Search⌘K

Algorithmadvanced

Iterative back-projection super-resolution

Also called Irani-Peleg super-resolution.

Refine a high resolution estimate by simulating each low resolution frame and back-projecting the differences. With the mirrored PSF as kernel it is Landweber on the stacked frames.

Time
Θ(T K n m) worst · average · best
Space
Θ(n) extra
Where
K = the number of frames; T = the number of iterations; m = the number of nonzero PSF entries; n = the number of high resolution pixels
Properties
deterministiciterativelinearneeds early stoppingneeds registration
Origin
Michal Irani, Shmuel Peleg, 1991

Iterative back-projection (IBP) is the method of Irani and Peleg (1991) for multi-frame super-resolution. It starts from a guess of the high resolution image. It simulates each low resolution frame from the guess: shift, blur, keep every LL-th pixel. It compares each simulated frame with the observed frame, spreads the difference back onto the high resolution grid with a back projection kernel, and adds the average of these corrections to the guess. With the mirrored PSF as the kernel, the update is x←x+ωAT(y−Ax)x \leftarrow x + \omega A^T(y - Ax) for the stacked frame operator AA, which is the Landweber iteration with the step ω=β/K\omega = \beta/K. So all the Landweber facts apply: convergence to the minimum norm least squares solution for a small enough step, a monotone error with exact data, and semi-convergence with noise. When the subpixel shifts cover every position of the high resolution grid once, the method is a deblurring filter with the factors 1−(1−ω∣Hq∣2)T1 - (1 - \omega|H_q|^2)^T, the same as in Van Cittert deconvolution in its Landweber form. The shifts must be known; in practice they come from image registration.

In plain words

You have several small, blurred photos of the same scene. Each one is taken from a slightly different position, by a fraction of a pixel. You want one large, sharp picture. Start with any large picture, for example a plain gray one. For each small photo, ask what the camera would have recorded if the scene were your large picture: move it, blur it, and take every second or third pixel. Compare this with the real photo. Where they differ, spread the difference back over the large picture, at the right position. Average the corrections from all photos, add them, and repeat. After many rounds, your large picture explains all photos. If the photos are noisy, stop earlier, because late rounds start to copy the noise.

The problem

The unknown is a high resolution (HR) signal or image xx with nn pixels on a periodic grid. Frame k=1,…,Kk = 1, \ldots, K is

yk=D B Wk x+ek.y_k = D\,B\,W_k\,x + e_k .
  • WkW_k is the motion. Here it is an integer shift on the HR grid, (Wkx)j=x(j+sk) mod n(W_k x)_j = x_{(j + s_k) \bmod n}, so a shift of one HR pixel is a shift of 1/L1/L of a low resolution (LR) pixel. In 2D, sks_k is a pair.
  • BB is the blur: periodic convolution with the PSF hh, stored with its center at index 00. Its OTF is Hq=∑jhje−2πijq/nH_q = \sum_j h_j e^{-2\pi i jq/n}. The PSF includes the optics and the integration over the area of the sensor pixel.
  • DD is the decimation by the factor LL: (Dv)j=vjL(Dv)_j = v_{jL}. A frame has n/Ln/L pixels (n/L2n/L^2 in 2D).
  • eke_k is noise.

Stack the frames into y=Ax+ey = Ax + e with A=(DBW1;…;DBWK)A = (DBW_1; \ldots; DBW_K). The goal is an estimate of xx. The problem page explains when xx is determined by the frames.

The algorithm

U=DTU = D^T puts each LR pixel at its place on the HR grid and fills the rest with zeros. pp is the back projection kernel, applied by periodic convolution. The default is the mirrored PSF pj=h−jp_j = h_{-j}.

  1. IBP(y_1..y_K, s_1..s_K, h, p, L, beta, T, x0) ▷ default p = mirror of h, x0 = 0
  2. 1x ← x0
  3. 2repeat T times
  4. 3g ← 0
  5. 4for k = 1 .. K
  6. 5r_k ← y_k - D(h * W_k x) ▷ simulate frame k and compare
  7. 6g ← g + W_k^T (p * U r_k) ▷ back-project the residual
  8. 7x ← x + (beta / K) · g
  9. 8return x

Line L5 is the forward model of one frame. Line L6 zero-fills the residual, convolves it with pp and undoes the shift. Line L7 adds the average correction with the step β\beta. A common start is an average of the frames, interpolated to the HR grid; this changes only the start point.

Example

Take n=8n = 8, L=2L = 2, the PSF h0=2/3h_0 = 2/3, h±1=1/6h_{\pm 1} = 1/6, and the true signal x†=(0,0,6,0,0,0,0,0)x^\dagger = (0, 0, 6, 0, 0, 0, 0, 0). Two frames have the shifts s=0s = 0 and s=1s = 1. The blurred signal is (0,1,4,1,0,0,0,0)(0, 1, 4, 1, 0, 0, 0, 0), so the frames are y1=(0,4,0,0)y_1 = (0, 4, 0, 0), its even samples, and y2=(1,1,0,0)y_2 = (1, 1, 0, 0), its odd samples. The shifts 00 and 11 cover both residues mod 2, so the frames together see every sample of the blurred signal.

The OTF is Hq=2/3+(1/3)cos⁡(2πq/8)H_q = 2/3 + (1/3)\cos(2\pi q/8), which is 11, 0.90240.9024, 0.66670.6667, 0.43100.4310 and 1/31/3 for q=0,…,4q = 0, \ldots, 4. With pp the mirrored PSF and β=2\beta = 2, the step is ω=1\omega = 1, and the error at frequency qq is multiplied by 1−Hq21 - H_q^2 in each step, at worst by 8/98/9. The iterates from x0=0x_0 = 0:

TT xTx_T (rounded) ∥xT−x†∥\lVert x_T - x^\dagger\rVert
1 (0.1667,1.3333,3.0,1.3333,0.1667,0,0,0)(0.1667, 1.3333, 3.0, 1.3333, 0.1667, 0, 0, 0) 3.5512
2 (−0.1296,1.2593,3.8981,1.2593,−0.1296,−0.0741,−0.0093,−0.0741)(-0.1296, 1.2593, 3.8981, 1.2593, -0.1296, -0.0741, -0.0093, -0.0741) 2.7630
5 (−0.3368,0.7956,4.9671,0.7956,−0.3368,0.0368,0.0417,0.0368)(-0.3368, 0.7956, 4.9671, 0.7956, -0.3368, 0.0368, 0.0417, 0.0368) 1.6013
10 (−0.2268,0.3669,5.5726,0.3669,−0.2268,0.0950,−0.0430,0.0950)(-0.2268, 0.3669, 5.5726, 0.3669, -0.2268, 0.0950, -0.0430, 0.0950) 0.7580
20 (−0.0711,0.0885,5.9042,0.0885,−0.0711,0.0537,−0.0465,0.0537)(-0.0711, 0.0885, 5.9042, 0.0885, -0.0711, 0.0537, -0.0465, 0.0537) 0.2071
50 (−0.0021,0.0021,5.9979,0.0021,−0.0021,0.0020,−0.0020,0.0020)(-0.0021, 0.0021, 5.9979, 0.0021, -0.0021, 0.0020, -0.0020, 0.0020) 0.0059

The error falls in every step, and after 100 steps it is below 10−410^{-4}. The first iterate is x1=ωBTzx_1 = \omega B^T z, where z=(0,1,4,1,0,0,0,0)z = (0, 1, 4, 1, 0, 0, 0, 0) is the interlaced data. With only the first frame (s=0s = 0), the odd samples are never observed. The same iteration then converges, after 2000 steps, to (−0.3,1.2667,5.3667,1.2667,−0.3,−0.0667,0.0333,−0.0667)(-0.3, 1.2667, 5.3667, 1.2667, -0.3, -0.0667, 0.0333, -0.0667), which fits the one frame exactly but has the error 1.94941.9494: more iterations cannot replace a missing shift.

Correctness

The full proof is in proofs/correctness.md. The main facts:

  1. Landweber form (theorem). With pp the mirrored PSF, WkTPU=(DBWk)TW_k^T P U = (DBW_k)^T, so the update is x←x+ωAT(y−Ax)x \leftarrow x + \omega A^T(y - Ax) with ω=β/K\omega = \beta/K. For 0<ω<2/∥A∥20 < \omega < 2/\lVert A\rVert^2 and x0=0x_0 = 0 the iterates converge to the minimum norm least squares solution A+yA^{+}y. With exact data the error never grows.
  2. Complete set of shifts (theorem). If the shifts take each residue mod LL exactly once (each pair of residues in 2D), then ∑kWkTUDWk=I\sum_k W_k^T U D W_k = I, so ATA=BTBA^TA = B^TB. The iterate is then the spectral filter x^T,q=(1−(1−ω∣Hq∣2)T) z^q/Hq\hat x_{T,q} = (1 - (1 - \omega|H_q|^2)^T)\,\hat z_q/H_q of the interlaced data z=∑kWkTUykz = \sum_k W_k^T U y_k: the Landweber factor with σ=∣Hq∣\sigma = |H_q|.
  3. The kernel condition (theorem, for a complete set of shifts). For any kernel pp, the error at frequency qq is multiplied by 1−ωPqHq1 - \omega P_q H_q in each step. The method converges for every x†x^\dagger if and only if ∣1−ωPqHq∣<1|1 - \omega P_q H_q| < 1 at every qq. This is the frequency form of the condition on the back projection kernel that Irani and Peleg give. It fails for p=δp = \delta and a PSF whose OTF is negative somewhere: for the box of width 5 on 16 points, H4=−1/5H_4 = -1/5 and the error grows by 1.21.2 per step with ω=1\omega = 1.
  4. Identifiability (theorem). If a residue mod LL is missing, AA has a null space and no method recovers xx from the frames alone. If every residue is present and Hq≠0H_q \ne 0 for all qq, AA is injective.
Proof: Iterative back-projection is Landweber for the stacked frame operator, and with a complete set of shifts it is a spectral filterfull

Setting. The high resolution signal xx has nn samples, with LL dividing nn (an image is the same with two indices, the 2D DFT and pairs of residues). Frame k=1,…,Kk = 1, \ldots, K is yk=Akxy_k = A_k x with Ak=DBWkA_k = D B W_k, where (Wkx)j=x(j+sk) mod n(W_k x)_j = x_{(j + s_k) \bmod n} for an integer shift sks_k, BB is periodic convolution with a real PSF hh (center at index 00), and (Dv)j=vjL(Dv)_j = v_{jL} for j=0,…,n/L−1j = 0, \ldots, n/L - 1. U=DTU = D^T puts vjv_j at index jLjL and zeros elsewhere. PP is periodic convolution with a real back projection kernel pp. The iteration of lines L1 to L7, from x0x_0, is

xt+1=xt+ω∑k=1KWkTPU(yk−Akxt),ω=β/K.x_{t+1} = x_t + \omega \sum_{k=1}^{K} W_k^T P U (y_k - A_k x_t), \qquad \omega = \beta / K.

The DFT is x^q=∑jxje−2πijq/n\hat x_q = \sum_j x_j e^{-2\pi i jq/n}, Hq=h^qH_q = \hat h_q and Pq=p^qP_q = \hat p_q.

Lemma 1 (adjoints). WkTW_k^T is the shift by −sk-s_k, DT=UD^T = U, and for h~j=h−j\tilde h_j = h_{-j} the convolution with h~\tilde h is BTB^T. So with p=h~p = \tilde h, WkTPU=(DBWk)T=AkTW_k^T P U = (D B W_k)^T = A_k^T.

Proof. WkW_k is a permutation matrix, so its transpose is its inverse, the shift by −sk-s_k. DD selects the rows jLjL of the identity, so DTD^T puts the entries back at those rows. Bij=h(i−j) mod nB_{ij} = h_{(i - j) \bmod n}, so (BT)ij=h(j−i) mod n=h~(i−j) mod n(B^T)_{ij} = h_{(j - i) \bmod n} = \tilde h_{(i - j) \bmod n}. Then (DBWk)T=WkTBTDT(DBW_k)^T = W_k^T B^T D^T. □\square

Claim 1 (Landweber). Let AA be the stacked operator with the blocks A1,…,AKA_1, \ldots, A_K and yy the stacked data. With p=h~p = \tilde h, the iteration is xt+1=xt+ωAT(y−Axt)x_{t+1} = x_t + \omega A^T (y - A x_t), the Landweber iteration for Ax=yAx = y with step ω\omega. Hence for 0<ω<2/∥A∥20 < \omega < 2/\lVert A \rVert^2 and x0=0x_0 = 0, xtx_t converges to the minimum norm least squares solution A+yA^{+} y, the residual norm ∥y−Axt∥\lVert y - Ax_t\rVert never grows, and for y=Ax†y = Ax^\dagger the error ∥xt−A+Ax†∥\lVert x_t - A^{+}Ax^\dagger \rVert never grows.

Proof. By Lemma 1, ∑kAkT(yk−Akx)=AT(y−Ax)\sum_k A_k^T (y_k - A_k x) = A^T (y - Ax). The convergence and monotonicity statements are the standard properties of Landweber. In the singular basis of AA (singular values σi\sigma_i), from x0=0x_0 = 0 the iterate has the filter factors 1−(1−ωσi2)t1 - (1 - \omega \sigma_i^2)^t, which tend to 11 for 0<ωσi2<20 < \omega\sigma_i^2 < 2, and the components in the null space of AA stay 00. The error component along a right singular vector with σi>0\sigma_i > 0 is multiplied by 1−ωσi2∈(−1,1)1 - \omega\sigma_i^2 \in (-1, 1) in each step, so its modulus does not grow; the residual components are multiplied by the same factors. □\square

The test compares the code with the dense Landweber iteration on the stacked matrix in rational arithmetic, and the two agree exactly.

Lemma 2 (complete set of shifts). Let M=UDM = UD, the diagonal mask that keeps the indices j≡0(modL)j \equiv 0 \pmod L. Then WkTMWkW_k^T M W_k keeps the indices jj with j≡sk(modL)j \equiv s_k \pmod L. So if the residues sk mod Ls_k \bmod L take each value of {0,…,L−1}\{0, \ldots, L-1\} exactly cc times, ∑kWkTMWk=c I\sum_k W_k^T M W_k = c\,I.

Proof. (WkTMWkx)i=(MWkx)i−sk=[ i−sk≡0 ] xi(W_k^T M W_k x)_i = (M W_k x)_{i - s_k} = [\, i - s_k \equiv 0 \,]\, x_i. Summing over kk counts, for each ii, the frames with sk≡is_k \equiv i, which is cc. □\square

Claim 2 (spectral filter). Let the residues take each value exactly once, so K=LK = L (K=L2K = L^2 pairs in 2D). Then for any kernel pp the error et=xt−x†e_t = x_t - x^\dagger for exact data yk=Akx†y_k = A_k x^\dagger satisfies

e^t+1,q=(1−ωPqHq) e^t,q.\hat e_{t+1, q} = (1 - \omega P_q H_q)\, \hat e_{t,q}.

So xt→x†x_t \to x^\dagger for every x†x^\dagger if and only if ∣1−ωPqHq∣<1|1 - \omega P_q H_q| < 1 at every frequency qq. With p=h~p = \tilde h the factor is 1−ω∣Hq∣21 - \omega |H_q|^2, and from x0=0x_0 = 0

x^t,q=(1−(1−ω∣Hq∣2)t) z^qHq,z=∑kWkTUyk,\hat x_{t,q} = \bigl(1 - (1 - \omega |H_q|^2)^t\bigr)\, \frac{\hat z_q}{H_q}, \qquad z = \sum_k W_k^T U y_k,

for every data yy (not only exact data), at each qq with Hq≠0H_q \ne 0.

Proof. BB, PP and WkW_k are circulant, so they commute. With yk=Akx†y_k = A_k x^\dagger, the update of the error is et+1=et−ω∑kWkTPUDBWket=et−ωP(∑kWkTMWk)Bet=(I−ωPB)ete_{t+1} = e_t - \omega \sum_k W_k^T P U D B W_k e_t = e_t - \omega P \bigl(\sum_k W_k^T M W_k\bigr) B e_t = (I - \omega P B) e_t by Lemma 2 with c=1c = 1. In the Fourier basis PBPB is multiplication by PqHqP_q H_q. The factor (1−ωPqHq)t(1 - \omega P_q H_q)^t tends to 00 if and only if its modulus is below 11; if it is 11 or more at some qq, the error with only that frequency (and −q-q for a real signal) does not tend to 00. For general data and p=h~p = \tilde h, ∑kWkTBTUyk=BTz\sum_k W_k^T B^T U y_k = B^T z and ∑kAkTAk=BTB\sum_k A_k^T A_k = B^T B by Lemma 2, so the iteration is xt+1=(I−ωBTB)xt+ωBTzx_{t+1} = (I - \omega B^T B)x_t + \omega B^T z. By induction xt=ω∑j<t(I−ωBTB)jBTzx_t = \omega \sum_{j<t} (I - \omega B^T B)^j B^T z, and in the Fourier basis this is ω∑j<t(1−ω∣Hq∣2)j Hq‾ z^q\omega \sum_{j<t}(1 - \omega|H_q|^2)^j\, \overline{H_q}\, \hat z_q, whose geometric sum is the formula. □\square

So with a complete set of shifts the multiframe problem is a deblurring problem on the high resolution grid, and the factors are the Landweber factors 1−(1−ωσ2)t1 - (1 - \omega\sigma^2)^t with σ=∣Hq∣\sigma = |H_q|. The kernel condition ∣1−ωPqHq∣<1|1 - \omega P_q H_q| < 1 is the frequency form of the condition on the back projection kernel; it fails for p=δp = \delta and a PSF whose OTF is negative somewhere, as for the Van Cittert iteration.

Claim 3 (identifiability). If the residues of the shifts do not cover {0,…,L−1}\{0, \ldots, L-1\}, AA has a nontrivial null space. If they cover it and Hq≠0H_q \ne 0 for all qq, AA is injective.

Proof. If BB is singular, any v≠0v \ne 0 with Bv=0Bv = 0 gives Av=0Av = 0. Otherwise, let the residue rr be missing, let ee be the unit vector at index rr, and let v=B−1e≠0v = B^{-1} e \ne 0. Since WkW_k and BB commute, Akv=DWkeA_k v = D W_k e, which reads ee at the indices jL+sk≡sk≢rjL + s_k \equiv s_k \not\equiv r, where ee is 00. So Av=0Av = 0. If the residues are covered, ATA=∑kAkTAk⪰BT(∑k∈SWkTMWk)B=BTBA^T A = \sum_k A_k^T A_k \succeq B^T (\sum_{k \in S} W_k^T M W_k) B = B^T B for a subset SS with each residue once, and BTBB^T B is invertible when every Hq≠0H_q \ne 0. □\square

A shift by a multiple of LL (a whole low resolution pixel) gives no new information. In the test, two frames with the shifts 00 and 22 for L=2L = 2 give the same data for two signals that differ at the odd indices, and the iterate from 00 keeps those entries at 00. ■\blacksquare

Complexity

In the real-RAM model, one iteration costs, for each frame, one shift (Θ(n)\Theta(n)), one direct periodic convolution with mm nonzero PSF entries (Θ(nm)\Theta(nm)), the decimation, the zero fill, one convolution with pp (also mm entries for the mirrored PSF) and one shift. So one iteration costs Θ(Knm)\Theta(Knm), and TT iterations cost Θ(TKnm)\Theta(TKnm). With the FFT each convolution costs Θ(nlog⁡n)\Theta(n \log n) for nn a power of two. The extra space is Θ(n)\Theta(n) for xx and gg, plus one frame for the residual.

The number of iterations follows the Landweber rules. With exact data and a complete set of shifts, the error at frequency qq falls like ∣1−ω∣Hq∣2∣T|1 - \omega|H_q|^2|^T, so a relative error ε\varepsilon at that frequency takes about log⁡(1/ε)/(ω∣Hq∣2)\log(1/\varepsilon)/(\omega|H_q|^2) steps for small ∣Hq∣|H_q|. With noise of level δ\delta, TT is the regularization parameter; the discrepancy principle chooses it when δ\delta is known.

Properties

  • Linear in the data for fixed shifts and a fixed pp. The method has no noise model and does not keep the estimate nonnegative; the example has negative entries.
  • With the mirrored PSF it is a gradient method for 12∑k∥yk−DBWkx∥2\frac12\sum_k\lVert y_k - DBW_kx\rVert^2, so each step does not increase this sum for 0<ω≤2/∥A∥20 < \omega \le 2/\lVert A\rVert^2.
  • The components of xx in the null space of AA stay at their values in x0x_0. With x0=0x_0 = 0 they stay 00.
  • The result depends on the registration. A wrong shift puts the residual of a frame at the wrong place, and the iteration then fits an inconsistent model.

Variants and improvements

  • Other back projection kernels. Irani and Peleg allow a kernel pp different from the PSF; a sharper pp speeds up the high frequencies but must keep ∣1−ωPqHq∣<1|1 - \omega P_q H_q| < 1. Only the mirrored PSF makes the method a gradient method for general shifts.
  • Regularized forms. Add −ωλ x-\omega\lambda\, x or the gradient of a smoothness term to the step. This is gradient descent on the Tikhonov or a total variation objective, and the iteration then needs no early stopping. Elad and Feuer (1997) put the multiframe problem in the maximum likelihood, MAP and projection onto convex sets frameworks.
  • Robust data term. Farsiu, Robinson, Elad and Milanfar (2004) replace the squared residual by its L1 norm. For pure translation the L1 fit of the stacked frames is a pixelwise median on the HR grid (robust shift-and-add), and the L2 fit is the pixelwise mean, followed by deblurring. This makes the method robust to outliers and registration errors.
  • Faster solvers. The same least squares problem can be solved by CGLS on the stacked operator, which needs far fewer iterations than Landweber.
  • Projection onto constraints. Clip xx to [0,xmax⁡][0, x_{\max}] after each step, which is projected Landweber.

When to use it

Use IBP when you have several registered frames of a static scene with subpixel shifts, a known PSF and moderate noise, and you want a simple method that is easy to check. It is a good baseline and a teaching example of the forward model DBWkDBW_k. For pure translations and many frames, shift-and-add followed by deblurring is cheaper and gives the same least squares answer. For astronomical data with flux to keep and bad pixels, use drizzle. For noisy data use a regularized form, and for few iterations use CGLS.

Pitfalls

  • Missing shifts. Frames whose shifts are equal mod LL add no new samples. A shift by a whole LR pixel is useless for resolution.
  • Wrong registration. Errors of a fraction of an HR pixel blur the result, and outliers in the motion estimate create ghosts. Register on the frames with a method that reaches subpixel accuracy.
  • A kernel that breaks the condition. With p=δp = \delta the method is the Van Cittert iteration on the HR grid and diverges where the OTF is negative, as for a box pixel integration with a large fill factor.
  • Too large a step. ω\omega above 2/∥A∥22/\lVert A\rVert^2 makes the iteration diverge. With h≥0h \ge 0 and ∑h=1\sum h = 1 and a complete set of shifts, ∥A∥=1\lVert A\rVert = 1, so any 0<β/K<20 < \beta/K < 2 works.
  • Semi-convergence. With noise, the error first falls and then rises. Without a known noise level, any stopping rule is a heuristic.
  • Boundaries. Real frames are not periodic. The periodic model gives ringing at the border unless you pad the HR grid.

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.

iterative_back_projection_super_resolution.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/iterative-back-projection-super-resolution/. The authors are listed in prov/KACAK6.jsonl.
"""Iterative back-projection (Irani-Peleg) super-resolution.

The high resolution (HR) unknown x is a signal of length n or an image of
n1 x n2 pixels. Frame k is y_k = D B W_k x: W_k is an integer shift of the HR
grid, (W_k x)_j = x_{(j + s_k) mod n}; B is periodic convolution with the PSF
h (center at index 0); D keeps every L-th sample, (D v)_j = v_{j L}. So a
frame has n / L samples (n1 / L x n2 / L for an image). The update is

    x <- x + (beta / K) sum_k W_k^T (p * U (y_k - D B W_k x)),

with U = D^T (zero fill) and p the back projection kernel. With p = mirror(h)
it is the Landweber iteration for the stacked operator A = (D B W_k)_k with
the step omega = beta / K. Works with float and with fractions.Fraction values.
"""


def _is_image(x):
    return bool(x) and isinstance(x[0], (list, tuple))


def _conv1(x, h):
    n = len(x)
    nz = [(j, v) for j, v in enumerate(h) if v != 0]
    return [sum(v * x[(i - j) % n] for j, v in nz) for i in range(n)]


def _conv2(x, h):
    n1, n2 = len(x), len(x[0])
    nz = [(p, q, h[p][q]) for p in range(len(h)) for q in range(len(h[0])) if h[p][q] != 0]
    return [[sum(v * x[(i - p) % n1][(j - q) % n2] for p, q, v in nz) for j in range(n2)] for i in range(n1)]


def blur(x, h):
    """The periodic convolution h * x (signal or image), kernel centered at index 0."""
    return _conv2(x, h) if _is_image(x) else _conv1(x, h)


def mirror(h):
    """The kernel h(-r), so that blur(., mirror(h)) is the adjoint of blur(., h) for real h."""
    if _is_image(h):
        n1, n2 = len(h), len(h[0])
        return [[h[(-i) % n1][(-j) % n2] for j in range(n2)] for i in range(n1)]
    n = len(h)
    return [h[(-j) % n] for j in range(n)]


def warp(x, s):
    """(W x)_j = x_{(j + s) mod n}; s is an int for a signal and a pair for an image."""
    if _is_image(x):
        n1, n2 = len(x), len(x[0])
        a, b = s
        return [[x[(i + a) % n1][(j + b) % n2] for j in range(n2)] for i in range(n1)]
    n = len(x)
    return [x[(j + s) % n] for j in range(n)]


def warp_adjoint(x, s):
    """W^T, the shift by -s."""
    if _is_image(x):
        return warp(x, (-s[0], -s[1]))
    return warp(x, -s)


def decimate(x, factor):
    """D: keep the samples with index j L (rows and columns i L, j L for an image)."""
    if _is_image(x):
        return [row[::factor] for row in x[::factor]]
    return x[::factor]


def upsample(y, factor):
    """U = D^T: put y_j at index j L and zeros elsewhere."""
    if _is_image(y):
        n2 = len(y[0]) * factor
        zero = 0 * y[0][0]
        out = []
        for row in y:
            full = [zero] * n2
            full[::factor] = row
            out.append(full)
            out.extend([zero] * n2 for _ in range(factor - 1))
        return out
    zero = 0 * y[0]
    out = [zero] * (len(y) * factor)
    out[::factor] = y
    return out


def forward(x, shift, h, factor):
    """Simulate one low resolution frame: D B W_k x."""
    return decimate(blur(warp(x, shift), h), factor)


def back_project(r, shift, p, factor):
    """W_k^T (p * U r): spread a low resolution residual back onto the HR grid."""
    return warp_adjoint(blur(upsample(r, factor), p), shift)


def _sub(a, b):
    if _is_image(a):
        return [[u - v for u, v in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [u - v for u, v in zip(a, b)]


def _axpy(x, c, g):
    if _is_image(x):
        return [[u + c * v for u, v in zip(ra, rb)] for ra, rb in zip(x, g)]
    return [u + c * v for u, v in zip(x, g)]


def _zeros_like(x):
    if _is_image(x):
        return [[0 * v for v in row] for row in x]
    return [0 * v for v in x]


def hr_zeros(frames, factor):
    """The zero HR signal or image for frames decimated by factor."""
    return _zeros_like(upsample(frames[0], factor))


def ibp(frames, shifts, h, factor, p=None, beta=1, iters=10, x0=None, callback=None):
    """Run iters steps of iterative back-projection.

    frames[k] is y_k and shifts[k] is s_k. p is the back projection kernel
    (default mirror(h), which gives Landweber). The step is beta / K.
    callback(t, x) is called after step t, if given. Returns the last x.
    """
    if p is None:
        p = mirror(h)
    big_k = len(frames)
    x = hr_zeros(frames, factor) if x0 is None else x0  # @line L1
    for t in range(iters):  # @line L2
        g = _zeros_like(x)  # @line L3
        for y, s in zip(frames, shifts):  # @line L4
            r = _sub(y, forward(x, s, h, factor))  # @line L5
            g = _axpy(g, 1, back_project(r, s, p, factor))  # @line L6
        x = _axpy(x, beta / big_k, g)  # @line L7
        if callback is not None:
            callback(t + 1, x)
    return x  # @line L8


def shift_and_add(frames, shifts, factor):
    """sum_k W_k^T U y_k divided by the number of frames that hit each HR pixel (0 where none)."""
    acc = hr_zeros(frames, factor)
    hits = hr_zeros(frames, factor)
    for y, s in zip(frames, shifts):
        acc = _axpy(acc, 1, warp_adjoint(upsample(y, factor), s))
        ones = [[1] * len(y[0]) for _ in y] if _is_image(y) else [1] * len(y)
        hits = _axpy(hits, 1, warp_adjoint(upsample(ones, factor), s))
    if _is_image(acc):
        return [[a / c if c else a for a, c in zip(ra, rc)] for ra, rc in zip(acc, hits)]
    return [a / c if c else a for a, c in zip(acc, hits)]


def residual_norm2(x, frames, shifts, h, factor):
    """sum_k ||y_k - D B W_k x||^2."""
    total = 0
    for y, s in zip(frames, shifts):
        r = _sub(y, forward(x, s, h, factor))
        vals = [v for row in r for v in row] if _is_image(r) else r
        total += sum(abs(v) ** 2 for v in vals)
    return total


def covers_all_residues(shifts, factor):
    """True when the shifts take every residue mod L (every pair of residues for an image)."""
    if shifts and isinstance(shifts[0], (list, tuple)):
        got = {(a % factor, b % factor) for a, b in shifts}
        return len(got) == factor * factor
    return len({s % factor for s in shifts}) == factor
test_iterative_back_projection_super_resolution.py 183 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/iterative-back-projection-super-resolution/. The authors are listed in prov/KACAK6.jsonl.

import cmath
import math
import random
from fractions import Fraction as F

from iterative_back_projection_super_resolution import (
    back_project,
    covers_all_residues,
    forward,
    ibp,
    mirror,
    residual_norm2,
    shift_and_add,
)


def dft(x):
    n = len(x)
    return [sum(x[j] * cmath.exp(-2j * math.pi * j * k / n) for j in range(n)) for k in range(n)]


def norm(v):
    if v and isinstance(v[0], list):
        v = [t for row in v for t in row]
    return math.sqrt(sum(abs(t) ** 2 for t in v))


def sub(a, b):
    if a and isinstance(a[0], list):
        return [[p - q for p, q in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [p - q for p, q in zip(a, b)]


def psf(n, taps):
    h = [0] * n
    for d, v in taps.items():
        h[d % n] += v
    return h


def frames_of(x, shifts, h, factor):
    return [forward(x, s, h, factor) for s in shifts]


def test_back_projection_is_the_adjoint_for_the_mirrored_kernel():
    rng = random.Random(1)
    n, factor = 12, 3
    h = [rng.random() for _ in range(n)]
    for s in (0, 1, 5, 11):
        x = [rng.gauss(0, 1) for _ in range(n)]
        r = [rng.gauss(0, 1) for _ in range(n // factor)]
        ax = forward(x, s, h, factor)
        lhs = sum(a * b for a, b in zip(ax, r))
        rhs = sum(a * b for a, b in zip(x, back_project(r, s, mirror(h), factor)))
        assert abs(lhs - rhs) <= 1e-10 * norm(ax) * norm(r)
    h2 = [[rng.random() for _ in range(6)] for _ in range(6)]
    for s in ((0, 0), (1, 4), (5, 3)):
        x = [[rng.gauss(0, 1) for _ in range(6)] for _ in range(6)]
        r = [[rng.gauss(0, 1) for _ in range(3)] for _ in range(3)]
        ax = forward(x, s, h2, 2)
        lhs = sum(a * b for ra, rb in zip(ax, r) for a, b in zip(ra, rb))
        bp = back_project(r, s, mirror(h2), 2)
        rhs = sum(a * b for ra, rb in zip(x, bp) for a, b in zip(ra, rb))
        assert abs(lhs - rhs) <= 1e-10 * norm(ax) * norm(r)


def test_equals_landweber_on_the_stacked_matrix_exactly():
    rng = random.Random(2)
    for _ in range(3):
        n, factor = 6, 2
        raw = [rng.randint(0, 3) for _ in range(n)]
        raw[0] += 2
        h = [F(v, sum(raw)) for v in raw]
        shifts = rng.sample(range(n), 3)
        rows = []
        for s in shifts:
            cols = [forward([F(int(i == j)) for i in range(n)], s, h, factor) for j in range(n)]
            rows.extend([cols[j][r] for j in range(n)] for r in range(n // factor))
        y = [F(rng.randint(-4, 4)) for _ in rows]
        frames = [y[k * (n // factor):(k + 1) * (n // factor)] for k in range(len(shifts))]
        beta = F(rng.randint(1, 3), 2)
        omega = beta / len(shifts)
        iters = rng.randint(1, 4)
        x = [F(0)] * n
        for _ in range(iters):
            res = [yi - sum(a * b for a, b in zip(row, x)) for yi, row in zip(y, rows)]
            x = [x[j] + omega * sum(rows[i][j] * res[i] for i in range(len(rows))) for j in range(n)]
        assert ibp(frames, shifts, h, factor, beta=beta, iters=iters) == x


def test_filter_factors_with_a_complete_set_of_shifts():
    # With every residue mod L once, A^T A = B^T B, so the iterate is a spectral
    # filter of z = sum_k W_k^T U y_k with factors 1 - (1 - omega |H_q|^2)^T.
    rng = random.Random(3)
    n, factor = 12, 3
    h = psf(n, {0: 0.5, 1: 0.2, -1: 0.2, 2: 0.05, -2: 0.05})
    shifts = [5, 1, 9]
    assert covers_all_residues(shifts, factor)
    y = [[rng.gauss(0, 1) for _ in range(n // factor)] for _ in shifts]
    beta, iters = 2.5, 7
    omega = beta / len(shifts)
    xq = dft(ibp(y, shifts, h, factor, beta=beta, iters=iters))
    zq = dft(shift_and_add(y, shifts, factor))
    hq = dft(h)
    for q in range(n):
        f = 1 - (1 - omega * abs(hq[q]) ** 2) ** iters
        expect = f * zq[q] / hq[q]
        assert abs(xq[q] - expect) <= 1e-9 * (1 + abs(expect))


def test_exact_data_converges_and_the_error_never_grows():
    n, factor = 16, 2
    h = psf(n, {0: F(2, 3), 1: F(1, 6), -1: F(1, 6)})
    hf = [float(v) for v in h]
    rng = random.Random(4)
    xt = [rng.choice([0.0, 0.0, 1.0, 4.0]) for _ in range(n)]
    shifts = [0, 1]
    y = frames_of(xt, shifts, hf, factor)
    errs = []
    ibp(y, shifts, hf, factor, beta=2.0, iters=220, callback=lambda t, x: errs.append(norm(sub(x, xt))))
    for a, b in zip(errs, errs[1:]):
        assert b <= a * (1 + 1e-12)
    assert errs[-1] < 1e-8 * norm(xt)


def test_delta_blur_and_a_complete_set_is_solved_in_one_step():
    rng = random.Random(5)
    n, factor = 9, 3
    delta = [F(1)] + [F(0)] * (n - 1)
    xt = [F(rng.randint(0, 9)) for _ in range(n)]
    shifts = [0, 4, 8]
    y = frames_of(xt, shifts, delta, factor)
    assert shift_and_add(y, shifts, factor) == xt
    assert ibp(y, shifts, delta, factor, beta=3, iters=1) == xt


def test_one_residue_twice_is_not_identifiable():
    n, factor = 8, 2
    delta = [F(1)] + [F(0)] * (n - 1)
    shifts = [0, 2]
    assert not covers_all_residues(shifts, factor)
    xt = [F(v) for v in (1, 2, 3, 4, 5, 6, 7, 8)]
    other = [v + (5 if j % 2 else 0) for j, v in enumerate(xt)]
    assert frames_of(xt, shifts, delta, factor) == frames_of(other, shifts, delta, factor)
    x = ibp(frames_of(xt, shifts, delta, factor), shifts, delta, factor, beta=1, iters=5)
    assert all(x[j] == 0 for j in range(1, n, 2))
    assert residual_norm2(x, frames_of(xt, shifts, delta, factor), shifts, delta, factor) == 0


def test_the_kernel_condition_decides_convergence():
    # Box of width 5 on 16 points: H_4 = -1/5. With a complete set of shifts and
    # beta = K the error at frequency q is multiplied by 1 - P_q H_q.
    n, factor = 16, 2
    h = psf(n, {d: 0.2 for d in range(-2, 3)})
    delta = [1.0] + [0.0] * (n - 1)
    shifts = [0, 1]
    xt = [math.cos(2 * math.pi * 4 * j / n) for j in range(n)]
    y = frames_of(xt, shifts, h, factor)
    e10 = norm(sub(ibp(y, shifts, h, factor, p=delta, beta=2.0, iters=10), xt))
    e20 = norm(sub(ibp(y, shifts, h, factor, p=delta, beta=2.0, iters=20), xt))
    assert abs(e20 / e10 - 1.2 ** 10) < 1e-6 * 1.2 ** 10
    errs = [norm(sub(ibp(y, shifts, h, factor, beta=2.0, iters=k), xt)) for k in (0, 5, 10, 30)]
    for a, b in zip(errs, errs[1:]):
        assert b <= a * (1 + 1e-12)
    assert errs[-1] < 0.5 * errs[0]


def test_two_dimensional_frames():
    n, factor = 8, 2
    w = {0: 0.8, 1: 0.1, n - 1: 0.1}
    h = [[w.get(i, 0.0) * w.get(j, 0.0) for j in range(n)] for i in range(n)]
    rng = random.Random(6)
    xt = [[rng.choice([0.0, 1.0, 2.0]) for _ in range(n)] for _ in range(n)]
    shifts = [(0, 0), (0, 1), (1, 0), (1, 1)]
    assert covers_all_residues(shifts, factor)
    y = frames_of(xt, shifts, h, factor)
    x = ibp(y, shifts, h, factor, beta=4.0, iters=150)
    assert norm(sub(x, xt)) < 1e-7 * norm(xt)
    # Three of the four shifts leave a quarter of the HR pixels unseen.
    assert not covers_all_residues(shifts[:3], factor)

History

Irani and Peleg (1991) built an HR image from several LR frames of a scene. They first registered the frames, then improved the estimate by iterative back-projection of the simulation errors. The name recalls the back projection of computed tomography. Their 1993 paper combined it with motion analysis to handle occlusion and transparency. Elad and Feuer (1997) wrote the general model with warp, blur and decimation in matrix form and solved it by maximum likelihood, MAP and projection onto convex sets, which showed that IBP is one member of a family of least squares methods. Farsiu, Robinson, Elad and Milanfar (2004) made the method robust with an L1 data term.

References

  1. Michal Irani and Shmuel Peleg, Improving resolution by image registration, CVGIP: Graphical Models and Image Processing 53(3), 1991, 231 to 239, the iterative back-projection update and the choice of the back projection kernel
  2. Michal Irani and Shmuel Peleg, Motion analysis for image enhancement: resolution, occlusion, and transparency, Journal of Visual Communication and Image Representation 4(4), 1993, 324 to 335, the back-projection method with motion analysis, and its convergence condition on the back projection kernel (general locator)
  3. Michael Elad and Arie Feuer, Restoration of a single superresolution image from several blurred, noisy, and undersampled measured images, IEEE Transactions on Image Processing 6(12), 1997, 1646 to 1658, the model with warp, blur and decimation for each frame, and the maximum likelihood, MAP and POCS solutions
  4. 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, the robust L1 data term, shift-and-add for pure translation, and the comparison with earlier methods

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
  • a scene preset for the example