Fractional Upscale Factors: Why 1.25× Can Lose to 1.333×
Almost every upscaling guide tests 2× and 4×. Almost every real job asks for something else. A 1920×1080 source going to 2560×1440 is 1.333×, not 2×. A 1080p frame into 1440p vertical is 1.778×. Full HD to DCI 2K is 1.067×. Those factors are ratios of small integers, and small-integer ratios do not behave like 2×. I measured seven exact fractional factors on a real photograph and found something that should not be possible under the usual model: the larger factor scored better than the smaller one. 4/3 (1.333×) beat 5/4 (1.25×) by 0.64 dB in five out of five crops. This page is the measurement, the mechanism I could and could not confirm, and the one decision that actually pays at fractional ratios.
Why fractional factors are a different problem
A 2× upscale asks the resampler to place output sample j at source coordinate j/2. Half the output pixels land exactly on a source pixel; the other half land exactly halfway between two. Two phase positions, perfectly repeating, and the halfway case is the smoothest thing a kernel can be asked to do.
A 4/3 upscale asks output pixel j to sample source coordinate 0.75·j. The fractional part cycles through four values — 0, 0.75, 0.5, 0.25 — before repeating. A 5/4 factor cycles through five: 0, 0.8, 0.6, 0.4, 0.2. A 7/5 would cycle through five irregular values. This is not a cosmetic difference. Each phase position corresponds to a different kernel weight vector, and a different amount of the kernel falling outside the source pixel grid.
The intuition most guides carry is that fractional factors are uniformly worse than integer ones and that the smaller the factor, the better the result. The second half of that sentence is what I tested, and it is false.
Experiment 1: the recovery curve is not monotonic
I built seven source images from one 1080×1620 photograph by area-average downscaling at exact rational factors, then upscaled each back to 1080×1620 with Lanczos-3 and compared against the original. Because every factor is n/d with both dimensions divisible, the round-trip is grid-aligned and the comparison is exact — no resampling of the reference.
| Factor | Source | PSNR | Gradient retained | HF energy retained |
|---|---|---|---|---|
| 6/5 = 1.200 | 900×1350 | 36.005 dB | 100.45% | 70.08% |
| 5/4 = 1.250 | 864×1296 | 34.978 dB | 100.17% | 67.07% |
| 4/3 = 1.333 | 810×1215 | 35.821 dB | 99.34% | 60.01% |
| 3/2 = 1.500 | 720×1080 | 33.932 dB | 96.90% | 50.15% |
| 5/3 = 1.667 | 648×972 | 33.708 dB | 93.22% | 42.18% |
| 2/1 = 2.000 | 540×810 | 32.932 dB | 88.09% | 29.69% |
| 3/1 = 3.000 | 360×540 | 30.288 dB | 75.49% | 11.80% |
The trend from 4/3 onward is what you expect: more magnification, more loss. But look at the top three rows. 5/4 discards less information than 4/3 — its source is 864 pixels wide instead of 810 — and it keeps 100.17% of the gradient against 4/3's 99.34%, and 67% of the high-frequency energy against 60%. It should win on both counts. It loses by 0.86 dB.
Gradient and HF retention are monotonic across the whole series, as they must be. PSNR is not. That split is the interesting part: the two metrics are measuring different things, and only one of them tracks the factor.
Experiment 2: it is not one unlucky crop
One image at one size could be a coincidence of content. I cut five 360×540 crops from non-overlapping regions and repeated the full series on each, using only exact factors so each crop's grid stays aligned.
| Crop origin | 6/5 | 5/4 | 4/3 | 3/2 | 5/3 | 2/1 |
|---|---|---|---|---|---|---|
| 0, 0 | 35.520 | 34.118 | 35.550 | 33.154 | 33.618 | 33.482 |
| 180, 270 | 42.950 | 42.110 | 42.234 | 40.566 | 41.333 | 41.338 |
| 360, 540 | 37.623 | 37.150 | 37.433 | 35.961 | 36.567 | 36.498 |
| 540, 810 | 41.657 | 41.836 | 42.463 | 40.312 | 41.117 | 40.972 |
| 720, 1080 | 40.103 | 39.479 | 40.211 | 37.968 | 35.891 | 34.905 |
| mean | 39.571 | 38.939 | 39.578 | 37.592 | 37.705 | 37.439 |
4/3 beat 5/4 in five crops of five, with a mean margin of +0.640 dB and a range from +0.124 dB to +1.432 dB. The effect is small in the tightest crop and over a decibel in the loosest, which is what a phase-driven artifact looks like rather than a content-driven one: it scales with how much edge structure sits under the grid.
What the numbers will not support. I could not attribute the dip to a single clean mechanism, and I am not going to invent one. Three candidate explanations all failed to survive their own test, and each failure is reported below rather than buried.
Experiment 3: the three explanations that did not work
Candidate 1 — "5/4 has a worse phase distribution"
If kernel phase irregularity were the cause, the error should cluster by phase position, and the factor with the most uneven phase spread should be worst. I measured mean absolute error per phase class for each factor:
| Factor | Phase class errors | Spread |
|---|---|---|
| 6/5 | 0.77 · 0.80 · 0.91 · 0.97 · 0.95 · 0.87 | 0.20 |
| 5/4 | 0.83 · 0.95 · 1.01 · 0.90 · 0.80 | 0.21 |
| 4/3 | 0.72 · 0.73 · 1.15 · 1.13 | 0.44 |
| 3/2 | 0.88 · 0.90 · 1.04 | 0.16 |
| 2/1 | 0.96 · 0.98 | 0.01 |
4/3 has the worst phase spread in the set — more than double 5/4's — and it is the one that wins. Phase irregularity is real, measurable, and not the explanation. The rounding of output coordinates also came back clean: on an impulse train, centroid offsets for 810→1080 were −0.012, +0.012, +0.012 and 0.000 px, i.e. sub-hundredth-pixel and not a systematic shift.
Candidate 2 — "the loss is in the downscale, not the upscale"
If BOX downscaling at 864 happened to interact badly with the content while 810 did not, then swapping the downscaler should shuffle the ranking. It did not. With Lanczos downscaling, the order became 39.25 / 38.17 / 37.64 / 36.29 / 33.25 for 6/5, 5/4, 4/3, 3/2, 2/1 — monotonic, and 5/4 no longer dips below 4/3. With bicubic downscaling, 38.71 / 37.69 / 37.23 / 35.95 / 32.97, also monotonic.
That is a genuine and useful negative result: the dip only exists when the downscale filter is BOX. A box filter is the only one in the set that aliases, and aliasing folds high-frequency content into the passband at a frequency determined by the ratio. With a properly low-passed downscale, the anomaly disappears entirely. So the honest finding is narrower than the headline: at fractional ratios, PSNR ordering is not a property of the factor alone — it depends on what the downscaler did to the spectrum before the upscaler ever ran.
Candidate 3 — "it is a checkerboard resonance at one period"
I swept synthetic checkerboards from 8 to 30 px period. The ranking shuffled completely between periods: at 10 px, 5/4 scored 26.03 dB while 4/3 scored 17.87 (5/4 far better); at 12 px, 5/4 scored 17.54 against 4/3's 24.85 (5/4 far worse); at 20 px, 5/4 won again at 29.45 vs 27.33. A ranking that inverts twice over a 2-pixel change in period is a resonance, not a rule. Checkerboards cannot support a claim about a general factor.
Experiment 4: step-chaining always loses, and the "smooth steps" advice is wrong twice
The most common practical advice for an awkward factor is to split it: go 810 → 935 → 1080 so each step is a gentler ~1.155×. Measured, every split loses to the single pass:
| Pipeline | PSNR | HF retained | vs one pass |
|---|---|---|---|
| one pass 810→1080 | 35.821 | 60.01% | — |
| two steps via 972 | 35.517 | 56.91% | −0.304 dB |
| two steps via 935 | 35.401 | 56.36% | −0.420 dB |
| two steps via 900 | 35.288 | 55.88% | −0.532 dB |
| three steps 880/970 | 35.126 | 52.59% | −0.695 dB |
The loss grows as the steps get more even, which is the opposite of the folklore's prediction. Two smooth 1.15× steps cost more than one rough 1.33× pass. The mechanism here is not mysterious: each pass applies a low-pass filter, and filters compose multiplicatively. Every intermediate is a fresh chance to lose high-frequency energy, and the measured HF column falls by 3 to 7 points per extra pass. This matches what the same test found at 2× and 4× on a different page in this series — chaining never pays, at any factor.
Related and equally settled: converting 4/3 into "2× then downscale" to reach the same target cost 0.164 dB (35.657 vs 35.821) and raised gradient retention to 100.60% while dropping HF to 57.92%. Higher gradient, lower high-frequency, worse PSNR — the extra pass buys apparent crispness by adding overshoot, not signal.
Experiment 5: sharpening pays in exact proportion to what was already lost
This is the one finding with a clean, actionable shape. For each factor I searched unsharp-mask settings (radius 0.6–1.5, amount 20–100%) for the best achievable PSNR and recorded the gradient retention of the unsharpened image next to the gain:
| Factor | Gradient before USM | Best gain | Settings |
|---|---|---|---|
| 6/5 | 100.45% | +0.055 dB | 30% / r0.6 |
| 5/4 | 100.17% | +0.012 dB | 20% / r0.6 |
| 4/3 | 99.34% | +0.119 dB | 40% / r0.6 |
| 3/2 | 96.90% | +0.059 dB | 40% / r0.6 |
| 5/3 | 93.22% | +0.172 dB | 80% / r0.6 |
| 2/1 | 88.09% | +0.375 dB | 100% / r0.8 |
| 3/1 | 75.49% | +0.298 dB | 100% / r1.0 |
Read the two numeric columns against each other. At 100% gradient retention sharpening is worth almost nothing (+0.055 dB) because there is nothing left to restore — the edge structure is already there and unsharp mask can only add overshoot. At 88% it is worth +0.375 dB, seven times more. The optimum amount also climbs with the loss: 20–30% when nothing is missing, 100% when a third of the gradient is gone.
The rule, stated as a rule. Measure gradient retention of your final image against a reference. Above ~99%, do not sharpen — the best unsharp mask setting gains 0.05 dB and you are paying in halos. Below ~90%, sharpen aggressively (80–100%, radius 0.6–1.0) because that is where the tool finally has something real to work with.
One caveat that matters for delivery: at 100% amount the overshoot count barely moves at fractional factors (0.96% of pixels more than 12 levels above reference at 4/3, 0.94% at 6/5) but climbs to 1.47% at 3×. Aggressive sharpening on a heavy upscale produces measurably more halo than the same settings on a light one — consistent with the fact that it is also doing more work.
Experiment 6: aliasing, measured as a fraction of total energy
Every factor discards the source band above the new Nyquist. What matters is whether that band folds back or disappears. I compared the energy the original holds above each factor's Nyquist against the energy the upscaled result holds there:
| Factor | LR Nyquist | GT energy above it | Output holds | Retained |
|---|---|---|---|---|
| 4/3 | 0.375 cyc/px | 0.067% | 0.023% | 34.5% |
| 3/2 | 0.333 cyc/px | 0.101% | 0.031% | 30.8% |
| 2/1 | 0.250 cyc/px | 0.198% | 0.043% | 21.5% |
The retained column is the amount of that out-of-band energy that reappears below the Nyquist line — i.e. folded back as alias. It is 34.5% at 4/3 and falls to 21.5% at 2×. Smaller factors alias proportionally more, which is a useful reminder that "gentler upscale" and "cleaner upscale" are different claims. Absolute levels are tiny on this photograph (0.067% of total energy is above the 4/3 Nyquist), so this is a correctness note, not a visible-artifact warning — on synthetic high-frequency content the same fold is catastrophic, which is exactly what the checkerboard sweep showed.
Experiment 7: engine, input and factor, ranked in dB
Experiment 2 established that the factor moves PSNR by 0.86 dB between 5/4 and 4/3 on this source. That number is useless on its own, because the question a real workflow asks is not "which factor" but "where do I spend the next hour of my life". There are three knobs available: which factor you choose, which resampling engine you call, and what you feed it. At 4/3 the first knob turns out to be worth more than ten times the second, and the third can erase the second entirely. I measured all three on the same source, same degrade, same measurement code.
The same 4/3 factor, five engines
Source is the 1080×1620 photograph from the other experiments. Degrade is an exact BOX downscale by 3/4 to 810×1215 — the ideal, anti-aliased case. Recover is one pass back to 1080×1620. PSNR is against the untouched photograph; HF% is high-frequency retention measured as mean absolute Laplacian relative to the original.
| Engine | PSNR (dB) | HF% of GT | PNG bytes |
|---|---|---|---|
| PIL − nearest | 34.544 | 111.7% | — |
| PIL − bilinear | 34.669 | 62.8% | — |
| PIL − bicubic | 35.749 | 73.8% | 1 311 852 |
| PIL − lanczos | 35.821 | 80.3% | 1 394 351 |
| ffmpeg swscale − lanczos | 35.830 | 79.9% | 2 668 970 |
| ffmpeg swscale − lanczos+accurate_rnd+full_chroma_int | 35.830 | 79.9% | 2 668 970 |
| ffmpeg swscale − bicubic | 35.736 | 75.0% | 2 606 913 |
| ffmpeg zscale (zimg) − lanczos | 35.824 | 79.8% | 2 658 220 |
Three separate Lanczos implementations — Pillow's, libswscale's, zimg's — land within 0.0094 dB of each other on PSNR and within 0.5 points on HF retention. They are not the same code: Pillow's output and swscale's differ by 56.9 dB PSNR against each other, which is a real numeric difference in the low bits. But that difference is invisible at the level of the reconstruction metric, because it is phase-identical. If your only decision is "Pillow or ffmpeg", the answer is whichever you already have loaded.
Negative result. accurate_rnd+full_chroma_int changed nothing —
the outputs were bit-identical (pairwise PSNR 999, i.e. zero difference). Those flags
affect the chroma-subsampled paths, and this test pins format=rgb24 on both sides of
the scale, so there is no chroma plane for them to touch. Anyone quoting those flags as a quality
fix for an RGB pipeline is repeating a forum post.
Kernel gain is not monotonic in the factor either
Having found that the engine barely matters at 4/3, the obvious follow-up: does that hold at other factors? Same source, exact BOX degrade at each factor, four kernels, PSNR against the original.
| Factor | nearest | bilinear | bicubic | lanczos | lanc − near |
|---|---|---|---|---|---|
| 4/3 (1.333×) | 34.544 | 34.669 | 35.749 | 35.821 | 1.277 |
| 3/2 (1.500×) | 30.944 | 33.167 | 33.842 | 33.932 | 2.988 |
| 2/1 (2.000×) | 31.304 | 31.676 | 32.641 | 32.932 | 1.628 |
| 3/1 (3.000×) | 29.230 | 29.699 | 30.169 | 30.288 | 1.058 |
| 4/1 (4.000×) | 27.522 | 27.843 | 28.225 | 28.283 | 0.761 |
Two things here contradict the advice this page opens with, and both are worth stating rather
than smoothing over. First, the value of a good kernel peaks at 3/2 (2.99 dB) and then
declines to 0.76 dB at 4×: past 3× there is so little to recover that a proper filter no longer
has much to win. Second, and stranger, nearest at 3/2 scores worse than
nearest at 2× (30.944 vs 31.304) even though the 3/2 case discards less of the
original. That is the same non-monotonicity Experiment 1 found in the recovery curve, showing up
in a second, independent measurement — this time as an ordering failure rather than a factor
anomaly. I could not attribute it to one clean mechanism: nearest takes a single source sample per
output pixel, so at 3/2 its sample positions land on an exact repeating pattern relative to the
source grid while at other ratios that pattern does not repeat within the frame, and the
reconstruction error then depends on which samples happen to be hit rather than on the ratio. The
usable conclusion is narrower and does not depend on that explanation: do not rank factors
by testing them with nearest.
What survives JPEG and WebP
A fractional-scale decision is almost never delivered as PNG. I re-measured the four Pillow kernels at 4/3 after realistic encodes, plus the wall-clock cost of each resize on this machine.
| Kernel | PNG | JPEG q90 | JPEG q75 | WebP q80 | ms / 1080×1620 |
|---|---|---|---|---|---|
| nearest | 34.544 | 34.099 | 33.780 | 33.707 | 2.1 |
| bilinear | 34.669 | 34.371 | 33.970 | 33.825 | 20.2 |
| bicubic | 35.749 | 35.343 | 34.852 | 34.762 | 27.8 |
| lanczos | 35.821 | 35.421 | 34.888 | 34.888 | 47.0 |
The nearest-to-lanczos gap is 1.28 dB and it survives encoding (1.32 dB at q90). The bicubic-to-lanczos gap is 0.072 dB and it does not reliably survive anything: 0.078 dB at q90, 0.036 dB at q75, 0.126 at WebP q80. For reference, dropping from PNG to JPEG q75 costs 0.93 dB — thirteen times the entire kernel difference. And the 0.072 dB costs 69% more compute than bicubic (47.0 vs 27.8 ms) and 23× the time of nearest.
The gap is inside the crop noise, and I can prove it
A 0.072 dB full-frame average deserves suspicion, so I split the photograph into eight disjoint regions and repeated the 4/3 comparison in each. Result: Lanczos beats bicubic in 4 of 8 crops, mean delta −0.019 dB, range −0.425 to +0.370. The full-frame win is not a consistent effect; it is the average of regions where bicubic happened to ring less against a handful where Lanczos resolved more. Anyone who reports a 0.07 dB kernel win from a single global PSNR has reported noise.
Compare that to the factor effect from Experiment 2: 0.86 dB between 5/4 and 4/3 across five of five crops in one direction. That is an order of magnitude larger than the kernel gap and it was unanimous, not 4-of-8. The practical ordering for a fractional delivery is therefore: pick the factor, then make sure the input is soft rather than blocky, and only then think about the kernel.
And the input matters more than the kernel
Same 4/3 recovery, six different ways of producing the 810×1215 input. This is the part that made me rewrite the advice in this section.
| Degrade chain | nearest | bicubic | lanczos | lanc − bicub |
|---|---|---|---|---|
| BOX (ideal) | 34.544 | 35.749 | 35.821 | +0.071 |
| bicubic down | 33.595 | 36.642 | 37.228 | +0.586 |
| bilinear down | 33.282 | 35.370 | 35.932 | +0.563 |
| BOX + JPEG q60 | 32.741 | 33.700 | 33.672 | −0.028 |
| bicubic down + JPEG q60 | 32.164 | 34.186 | 34.394 | +0.208 |
| bicubic down + JPEG q85 | 32.969 | 35.526 | 35.894 | +0.367 |
When the input was produced by a soft downscaler, Lanczos's advantage over bicubic is 0.586 dB — eight times what it was on the ideal BOX input. When the input has been through JPEG q60, the advantage collapses to 0.208 (or goes slightly negative for the BOX case). The kernel's headroom depends on how much high-frequency structure survived into the low-resolution image; a soft, correlated input gives a sharper filter something coherent to extrapolate, while a block-quantised input mostly gives it edges to overshoot.
I checked that last negative number rather than dropping it: six disjoint crops of the BOX+JPEG q60 case gave Lanczos minus bicubic a mean of −0.104 dB (range −0.275 to +0.134, 2 of 6 wins). It is a real, small, consistent loss. The usual fix — Gaussian pre-blur before Lanczos, "blur to kill ringing" — made it much worse: σ=0.4 cost 0.371 dB versus plain Lanczos, σ=0.6 cost 1.264, σ=0.8 cost 2.553. Pre-blurring before an upscale throws away the detail the upscale was supposed to reconstruct, and at fractional factors the amount it throws away is larger than the ringing it prevents.
The one-line version. At 4/3, swapping the kernel is worth 0.07 dB on an ideal input and 0.59 dB on a soft one; dropping the source through JPEG q60 instead of a clean downscale costs 2.1 dB outright; and choosing 4/3 over 5/4 is worth 0.86 dB. Engine ≪ factor. Spend the hour on the factor first, and do not trade a clean input for a fancier resampler.
Reproducing the engine comparison
import numpy as np, subprocess
from PIL import Image
gt = np.asarray(Image.open('photo.jpg').convert('RGB')) # 1620 x 1080
H, W = gt.shape[:2]
deg = Image.fromarray(gt).resize((W*3//4, H*3//4), Image.BOX) # exact 3/4
def psnr(a, b):
m = np.mean((a.astype(np.float64) - b.astype(np.float64)) ** 2)
return 10*np.log10(255.0**2/m) if m > 0 else 999.0
def hf(a):
y = (0.299*a[:,:,0] + 0.587*a[:,:,1] + 0.114*a[:,:,2]) / 255.0
lap = 4*y[1:-1,1:-1] - y[:-2,1:-1] - y[2:,1:-1] - y[1:-1,:-2] - y[1:-1,2:]
return float(np.abs(lap).mean())
deg.save('deg.png')
for flags in ('lanczos', 'lanczos+accurate_rnd+full_chroma_int', 'bicubic'):
subprocess.run(['ffmpeg','-y','-loglevel','error','-i','deg.png',
'-vf', f'format=rgb24,scale={W}:{H}:flags={flags},format=rgb24',
'-frames:v','1', f'{flags}.png'], check=True)
for name, k in (('pil_lanczos', Image.LANCZOS), ('pil_bicubic', Image.BICUBIC)):
up = np.asarray(deg.resize((W, H), k))
print(name, round(psnr(up, gt), 3), round(100*hf(up)/hf(gt), 1))
for name in ('lanczos', 'lanczos+accurate_rnd+full_chroma_int', 'bicubic'):
up = np.asarray(Image.open(f'{name}.png').convert('RGB'))
print(name, round(psnr(up, gt), 3), round(100*hf(up)/hf(gt), 1))
Two implementation notes so the numbers replicate: pin format=rgb24 on both sides
of the ffmpeg scale filter, because the default auto-inserted format conversion will silently route
through a subsampled YUV path and change every result; and degrade with Image.BOX at an
exact rational ratio, since a rounded target size turns the measurement into a phase test. Measured
with numpy 1.26.4, Pillow 12.2.0, ffmpeg 6.1.1, single 1080×1620 region, no multiprocessing.
What to do, concretely
- Do not split the factor. One pass at 4/3 beat every two-step and three-step chain by 0.30–0.70 dB. This is settled across every factor tested in this series.
- Do not convert to 2× and downscale. Cost 0.164 dB and added overshoot while lowering HF retention.
- Do not trust a PSNR ranking across factors if your downscaler aliases. The 5/4 anomaly vanished under Lanczos and bicubic downscaling and appeared only under BOX. If the source was produced by a naive decimator, your factor comparison is measuring the decimator.
- Check gradient retention before sharpening. Above 99%, skip it. Below 90%, apply 80–100% at radius 0.6–1.0.
- Do not shop for an engine. Three Lanczos implementations landed within
0.009 dB of each other and the bicubic-to-Lanczos gap at 4/3 (0.072 dB) is smaller than its own crop-to-crop
spread (−0.425 to +0.370, 4 of 8 crops). Spend the time on the factor or on the quality of the input
instead.
accurate_rnd+full_chroma_intproduced bit-identical output in an RGB pipeline. - Never pre-blur before a fractional upscale. Gaussian σ=0.4/0.6/0.8 before Lanczos cost 0.37/1.26/2.55 dB on JPEG-q60 input that ringing was supposedly the problem for.
- Prefer the larger factor when in doubt at fractional sizes. At equal downscale quality the cost of 4/3 over 5/4 is 0.86 dB of PSNR in the worst case and −0.61 dB in the Lanczos-downscaled case — but 4/3 also gives you 33% more pixels of output for a 1.78× pixel-count increase, and a 1440p delivery target needs the pixels regardless.
Cost, stated in pixels rather than adjectives
| Target | Output | Pixels vs 1080p |
|---|---|---|
| 1080p → DCI 2K (1.067×) | 2048×1080 | 1.07× |
| 1080p → 1440p (1.333×) | 2560×1440 | 1.78× |
| 1080p → UHD (2.0×) | 3840×2160 | 4.00× |
A 1440p delivery is 44% cheaper in output pixels than a UHD one and roughly half the separable-filter work (44.2M vs 99.5M tap operations at 6 taps). If the destination is a 1440p stream or a web embed, the fractional factor is not a compromise you are settling for — it is the correct target, and one pass with a proper resampler plus a conditional sharpening decision gets you there. For the broader question of how much of that output is genuinely recovered detail versus interpolated structure, the upscaling detail audit at upgolab.com covers the phase analysis that this page assumes.
Reproducing this
import numpy as np
from PIL import Image, ImageFilter
G = np.asarray(Image.open('photo.jpg').convert('RGB')).astype(np.float64)
GH, GW = G.shape[:2] # 1080 x 1620
def rs(a, size, k):
return np.asarray(Image.fromarray(np.clip(a,0,255).astype(np.uint8))
.resize(size, k)).astype(np.float64)
def psnr(a, b):
m = np.mean((a-b)**2)
return 10*np.log10(255.0**2/m) if m > 0 else 999.0
def grad(a):
y = (0.299*a[:,:,0] + 0.587*a[:,:,1] + 0.114*a[:,:,2]) / 255.0
gx = np.abs(np.diff(y, axis=1))[:-1,:]
gy = np.abs(np.diff(y, axis=0))[:,:-1]
return float(np.sqrt(gx**2 + gy**2).mean())
# exact rational factors: both dimensions divide cleanly
for n, d in [(6,5), (5,4), (4,3), (3,2), (5,3), (2,1), (3,1)]:
lw, lh = GW*d//n, GH*d//n
LR = rs(G, (lw, lh), Image.BOX) # area-average downscale
UP = rs(LR, (GW, GH), Image.LANCZOS) # single pass back up
print(f'{n}/{d} PSNR {psnr(UP,G):7.3f} grad {grad(UP)/grad(G)*100:6.2f}%')
# the sharpening sweep
for amt in [20, 40, 60, 80, 100]:
for rad in [0.6, 0.8, 1.0]:
im = Image.fromarray(np.clip(UP,0,255).astype(np.uint8))
S = np.asarray(im.filter(ImageFilter.UnsharpMask(
radius=rad, percent=amt, threshold=0))).astype(np.float64)
print(f'usm {amt}% r{rad} PSNR {psnr(S,G):7.3f}')
Two notes on running it. First, pick factors where both dimensions divide by the denominator —
1080 and 1620 both divide by 5, 4, 3 and 2, which is why those are the factors in the table; a
factor like 7/5 would need a source whose dimensions are multiples of 5, and cropping changes what
you are comparing. Second, the reported numbers depend on the downscaler. Run it with
Image.LANCZOS in place of Image.BOX and the 5/4 anomaly disappears, which
is the single most important thing this experiment established.
On a 5-year-old laptop this whole sweep runs in under six seconds per image at 1080×1620. There is no reason to guess at a fractional factor, and no reason to split one into steps.