Note (2017-03-20): the majority of this post was written on 19-21 February 2014. I no longer remember where I was going with this, and obviously that means I don’t remember what else I was going to write for this post. Have fun.
Sharpening filters are usually nonlinear, but blurring filters are usually linear. So deconvolution shall be used in the context of resharpening a blurred image. The term “filter” should also be assumed to refer exclusively to discrete filters.
Tl;dr: more of me writing about technical stuff I don’t know very well. Things may be hilariously inaccurate.
If you look at deconvolution in the frequency domain, it amounts to taking the reciprocal of the DTFT. Then doing an inverse transform provides a means to deconvolve using another convolution. Of course if you look at the Wikipedia article on deconvolution it’s not as simple as that. In addition, if we had the appropriate tools, an IIR filter would be more suitable. For instance, exact deconvolution of an (a,b,a) kernel (like Avisynth’s Blur, assuming that 2a+b=1) can be done with a causal/anticausal pair of filters with one pole each, provided that b>1/2. (Presumably this can be done with hqdn3d with negative values because it uses one-pole IIR filters, but I’ve never tried this. I don’t know of other Avisynth filters that intentionally provide IIR filters.)
On the other hand, with b≤1/2, the DTFT has zeros, so if you try to take the reciprocal of that you end up dividing by zero. You’re not allowed to do that, so don’t. (A similar caveat is that even if b is greater than but close to 1/2, you’re still dividing by a small number, which is also numerically unstable. Likewise for inverting Gaussian blurs.) What we can do is to try to approximate the reciprocal of the DTFT away from those zeros/small values.
Wiener deconvolution is one such approach (through minimising mean square error). It’s linear if you already have estimates on the source/noise power spectrum, but if you need to estimate those values from your input, it’s nonlinear. More importantly, this is inconvenient to implement within Avisynth because we can’t just take DFTs of our source.
An alternative approach is regularisation, which is actually a term encompassing a broad range of techniques, and in the context of deconvolution includes the aforementioned Wiener deconvolution. This is also easier to deal with in Avisynth (as long as we don’t insist on any particular method of regularisation) and since this is an encoding blog and not a DSP blog, we’re going to focus on that.
Regularisation is not so important if the convolution kernel of interest is exactly known and its inverse converges to zero quickly enough, but in practice the convolution isn’t exact (due to rounding errors), we don’t usually know the convolution kernel exactly either and sometimes the convolution kernel doesn’t have a convergent inverse (for example, if it has zeros in its DTFT). Regularisation, broadly defined, is any method by which we can mitigate the effects of these sources of inexactness in deconvolution.
A few months ago mirkosp posted a sample with some random vertical blurring in the middle of a scene. (The first link points to a reupload on MediaFire because posting links to others’ Dropbox accounts is probably not a good idea.)
<mirkosp> https://dl.dropboxusercontent.com/u/[redacted]/vshift.ts prunedtree think there could be a way to fix the weird vertical shift that starts at around halfway through this sample?
<mirkosp> i solved it with freezeframe in this case
<mirkosp> but i’ve seen it happen elsewhere and I had to just sort of live with it
<mirkosp> this is a helpful sample because the same exact frames are fine before the shift kicks in
<mirkosp> frame 125 is fine, 126 fucks up
My gut feel told me the vertical blurring was probably done with something like a (1/2,0,…,0,1/2) kernel, but neither (1/2,0,1/2) nor (1/2,0,0,0,1/2) looked quite right. The former blurred too much, the latter blurred too little, and while convolving with (1/2,0,0,1/2) seems to do the trick, it also introduces a half-pixel shift. However, this half-pixel shift is not really all that big of a deal since we can always use a resampler to get rid of it later on.
Side note: alternatively, we can adjust shift the kernel itself by half a pixel. Using sinc interpolation with binomial coefficients as a window, I got (27,-440,5940,16632,-11550,16632,5940,-440,27)/32768. (One nice thing about using binomial coefficients as a window is that the normalisation factors tend to end up as powers of two. Another nice thing is that it’s closely related to polynomial interpolation and Taylor series, but I don’t have a formal proof of this.) These shifted coefficients are fairly useless though, since there’s a simpler approach that also avoids dealing with the two distinct zeros in the DTFT. I plotted the frequency responses of both (1/2,0,0,1/2) and the aforementioned approximate shifted version (blue and green resp.; the frequencies are normalised so that ±0.5 is Nyquist frequency). Although they match up pretty closely for the lower frequencies, the difference gets progressively larger close to Nyquist. The two distinct zeros are at Nyquist and one-third Nyquist. (Note also that that the DTFT of a discrete signal is real iff it’s symmetric around zero, which is true in our case. The graphing program I use doesn’t support complex numbers so thank goodness I don’t have to hack up support using loads of trigonometric functions.)
The first insight I had was that this kernel only affected rows that were the same modulo 3, so we can just SeparateRows(3), do our deconvolution magic, WeaveRows(3), then fix the 1.5-pixel shift. (This is probably not ideal, but it’s simpler.) By looking at rows in groups of three, our convolution kernel is now just (1/2,1/2), which happens to be something I’ve previously covered in this blog, albeit in the context of temporal filtering rather than spatial filtering. As I was previously concerned with convolution in the time dimension, where ghosting from future frames is much more jarring than ghosting from past frames, that post focused on asymmetric filters. There’s no such limitation to bother with here.
Side note: we could also factor (1/2,0,0,1/2) as (1/2,1/2)∗(1,-1,1) then deconvolve those separately, but now instead of having one filter with real zeros in its DTFT, we have to deal with two filters with real zeros in their DTFTs. This doesn’t exactly help. If we try to use a Maclaurin series expansion on the reciprocal of the DTFT of (1,-1,1) or (1/2,0,0,1/2), our radius of convergence would be guaranteed to be less than one-third Nyquist because of the poles there. (I’m fudging a few things here. We should really be looking at the Laplace transform rather than DTFT, and also we can’t quite directly use Maclaurin series unless we perform a change of variables first. Maclaurin/Taylor series approaches generally also tend to be suboptimal in numerical analysis.)
Consider a doubly infinite sequence (…,1,-1,1,-1,1,1,-1,1,-1,1,…) which is symmetric around the (1,1) subsequence and alternates in sign everywhere else. Convolving this with (1/2,1/2) gives exactly a unit impulse (and zero everywhere else), so this can be considered to be an inverse of (1/2,1/2). It is in fact the only symmetric inverse; all other inverses are asymmetric. This inverse kernel doesn’t converge, but what we can do is to window it (which is also mentioned in the earlier post). I don’t have much signal processing knowledge so we’ll just have to resort to experimentation.
A rectangular window is extremely badly behaved; convolving it with (1/2,1/2) leads to a kernel of the form (±1/2,0,0,…,1,…,0,0,±1/2), the DTFT of which is just a (co)sine-squared curve, which has loads of distinct zeros. A triangular window is better, but still has plenty of oscillation in the frequency domain and the actual filtered image ends up with a lot of ringing. Gaussian and Gaussian-like windows (including higher-order B-spline windows and the aforementioned binomial coefficient windows) don’t have as much frequency-domain oscillation, but do have pretty significant overshoot.
What I suggested to mirkosp was a (1,-2,3,-4,5,-6,7,7,-6,5,-4,3,-2,1) kernel, which worked sorta fine, but could’ve been better yet—one simple improvement is to decrease the absolute value of every coefficient by 0.5. Because I like procrastinating actually important things I should be doing (like encoding Symphogear), I continued experimenting with the source.
One of the random thoughts that came to mind was to multiply a triangular window with an exponential window; I’ve previously tried this in deblending, which worked better than a pure exponential window or triangular window (though still terrible in general), so maybe it works better here? And it does: reduced frequency-domain oscillation, no overshoot, and reduced ringing too.
Our “regularisation” here could be as simple as making an edge mask to combine the deconvolved parts with the original, and then we’re done. Or actually, and I left this out earlier, the source has some annoying borders so getting rid of them (using BalanceBorders or the like) first is important. The logo is also affected by the deconvolution (since it’s not blurred like the rest of the frame), so delogoing should also be done prior.
Now, with all the above :blogging: written, a new approach to this deconvolution came to mind. If instead of using one symmetric kernel, we use two asymmetric kernels, and then combine the two together? I’m retard tier at filter design and the ad hoc windowing process above is rather questionable so let’s try looking for kernels that satisfy specific properties. For example, for an n-term kernel, after convolving it with (1/2,1/2), we can insist that it has unit sum and that its first, second, …, (n-1)th moments are zero. n variables, n equations.
For two terms these requirements give (3,-1)/2, for three terms (7,-4,1)/4, for four terms (15,-11,5,-1)/8, and these just so happen to be closely related to binomial coefficients. In fact, these coefficients turn up in A110814, although the signs are different every other row.
The idea is that with our asymmetric filter, we have ringing artifacts that only go upwards, so by applying the same filter upside down, we’d have artifacts going downwards. If we take the median of the upwards-filtered image, downwards-filtered image and the unfiltered image, we should end up with something pretty decent, without even explicitly resorting to using an edge mask! (Though an edge mask applied afterwards cleans up more residual ringing.) Another method of merging the up and down images is to choose the pixel that minimises the difference with the original, sort of like in MinBlur. (That said, if you do implement exactly like in MinBlur, this ends up being identical to using a median. In other words, I just unintentionally stumbled upon an optimisation for MinBlur.)
As symmetric even-length filters must have a zero in the DTFT at Nyquist frequency, there’s the dilemma of trying to approximate the reciprocal of small numbers (at frequencies near Nyquist) with other small numbers (because the DTFT of the “inverse” kernel also has a zero at Nyquist); using asymmetric filters would avoid this. The downside is that we lack obvious guarantees on the phase, which we’ve conveniently ignored up until now. Symmetric filters are necessarily either exactly in phase or antiphase, but with asymmetric filters the DTFT is not a real function and in general the phase is nonlinear, which results in phase distortion.
Side note: for odd-length symmetric filters, I’m taking the centre sample to be sampled at t=0 (and the rest of the samples are at integers), while for even-length symmetric filters, the two centre samples are at t=±1/2 (and the rest of the samples are at half-integers). Symmetric filters under alternative conventions (such as setting the first nonzero sample to t=0) are not necessarily in phase/antiphase. For the asymmetric filters, I’m taking the first sample to be at t=0.
I needed to get some other graphing program that supported complex numbers so these are made with one different from the previous graph. Again, x-axis is frequency in cycles per pixel (i.e. 2π radians/pixel), but this time the y-axis is in radians. Why different units? Idklol. I plotted the phase responses of the triangle-windowed asymmetric filter as well as the filter derived above. The jump of π radians at Nyquist frequency is due to the simple zero of the (1/2,1/2) kernel. There’s a fifty percent chance that I got the sign convention wrong, but don’t mind that.
Enough :words:, time for pictures. The pictures have been preprocessed by BalanceBorders and a delogoing filter I originally hacked up for the Animelo encodes. Other than these two filters, chroma is untouched.
Bonus feature (logs from 2017-02-24):
<mirkosp> who wrote unshift? i’m pretty sure it was somebody here
<mirkosp> maybe torchlight but dunno
<torchlight> no idea what that is
<torchlight> wait
<CoffeeFlux> lol
<torchlight> I may or may not have written something like that
<mirkosp> a script that takes 1080p crossconverted from 480
<CoffeeFlux> fucking torch
<mirkosp> or 486 perhaps, but same deal
<torchlight> oh, that’s definitely not mine
<CoffeeFlux> inb4 it was our resident corpse
<mirkosp> it does some magic number convolution to make a sharp shift with lotsa artifacts
<mirkosp> and then combines the two shifted clips in some way to restore a sharp clip with less artefacts
<torchlight> er
<torchlight> now that does sound familiar
<torchlight> ????
<mirkosp> i slightly modded it for a safer median that has no ringing leftovers at the cost of some very slight sharpness loss in very specific details
<mirkosp> i wanted to share the script online because this is definitely useful stuff, but I realized I can’t find the script around
<mirkosp> not on doom9 nor on avs wiki
<torchlight> dither_resize16(width(),height()/2,src_top=4,kernelv=”impulse 255 -247 219 -163 93 -37 9 -1 0″,fv=-1) < are these the magic coefficients
<mirkosp> YES
<torchlight> yeah that’s mine lol