Pillow’s Image.resize() is the de-facto reference for image resampling in
Python pipelines — which makes it awkward to accelerate with a GPU shader:
if your GPU output differs by even one grey level, every downstream
comparison becomes noise. This post shows a Vulkan compute resizer that
reproduces Pillow’s output exactly — 0 pixel diff — for all six
filters (nearest, box, bilinear, hamming, bicubic, lanczos), across
upscaling, downscaling, single-axis scaling, extreme ratios and grayscale.
Full example: p81_resize in VulkanExamples.
Why Pillow compatibility is non-trivial
Pillow does not do “mathematically nice” resampling. libImaging/Resample.c
works in a specific fixed-point scheme, and several of its details change
the output by ±1 if you don’t replicate them:
- Filters are evaluated in double, normalized to sum 1.0, then quantized
to 22-bit fixed point with round-half-away-from-zero:
(int)(v < 0 ? v - 0.5 : v + 0.5)wherev = coefficient * (1 << 22). - Downscaling widens the kernel:
filterscale = max(inSize/outSize, 1),support = filter.support * filterscale, and the kernel is sampled at(x + xmin - center + 0.5) / filterscale. - Edges clip the window and renormalize over the remaining taps — no coordinate clamping.
- Accumulation is int32:
ss = 1 << 21; ss += in * k, outputclamp(ss >> 22, 0, 255)(Pillow’sclip8). - The horizontal pass output is itself 8-bit — the vertical pass consumes the clamped intermediate, not higher-precision data.
- NEAREST doesn’t use the filter machinery at all. It goes through
ImagingScaleAffine, which accumulatesxo += scalein double — repeated additions drift off the closed form(x+0.5)*scale, flipping a few pixel picks at exact boundaries. You have to replicate the accumulation, not the formula.
Architecture: two separable passes, all conversions on GPU
in.ppm ──memcpy──> SSBO (packed u8, no RGBA expansion)
│ pass 1: horizontal, 1 invocation per output px
▼
tmp SSBO (RGBA u32, inH × outW)
│ pass 2: vertical
▼
out SSBO (RGBA u32, outH × outW)
│ pass 3: pack RGBA u32 → packed u8
▼
cached readback → out.ppm (a single memcpy)The host precomputes per-axis {xmin, nTaps} bounds and int32 coefficient
tables — the exact math from precompute_coeffs — and uploads them as
SSBOs. The shader never evaluates a filter kernel; it just accumulates:
layout(set = 0, binding = 0) readonly buffer In { uint inBuf[]; };
layout(set = 0, binding = 1) readonly buffer Bnd { ivec2 bnd[]; };
layout(set = 0, binding = 2) readonly buffer Cfs { int cf[]; };
layout(set = 0, binding = 3) writeonly buffer Out{ uint outBuf[]; };
layout(push_constant) uniform P {
uint inW, inH, outW, outH, ksize, axis, nComp;
};
void main() {
uint ox = gl_GlobalInvocationID.x, oy = gl_GlobalInvocationID.y;
if (ox >= outW || oy >= outH) return;
uint o = (axis == 0u) ? ox : oy;
ivec2 b = bnd[o];
ivec4 ss = ivec4(1 << 21); // Pillow's half-unit bias
for (int i = 0; i < b.y; ++i) {
int k = cf[o * ksize + uint(i)];
uint src = uint(b.x + i);
if (axis == 0u) { // packed input: byte extract
uint bi = (oy * inW + src) * nComp;
ss += ivec4(int(byteAt(bi)), int(byteAt(bi + 1u)),
int(byteAt(bi + 2u)), 0) * k;
} else { // RGBA u32 temp
uint px = inBuf[src * inW + ox];
ss += ivec4(int(px & 0xFFu), int((px >> 8) & 0xFFu),
int((px >> 16) & 0xFFu), 0) * k;
}
}
uint r = uint(clamp(ss.r >> 22, 0, 255));
uint g = uint(clamp(ss.g >> 22, 0, 255));
uint bch = uint(clamp(ss.b >> 22, 0, 255));
outBuf[oy * outW + ox] = r | (g << 8) | (bch << 16) | 0xFF000000u;
}Note the input stays packed (3 or 1 bytes per pixel): expanding to RGBA
on the CPU cost 124 ms for a 24 MP image — far more than the GPU dispatch
itself. The third pass packs the RGBA result back to u8 on the GPU so the
readback is a plain memcpy into the PPM payload.
NEAREST is expressed as a degenerate 1-tap resample — bounds = {sx, 1},
coefficient = 1 << 22 — so the same shader covers it:
double a0 = double(inSize) / outSize;
double xo = 0.5 * a0;
for (int xx = 0; xx < outSize; ++xx) {
int sx = int(xo); // floor, as COORD() does
a.bounds[xx * 2] = sx;
a.bounds[xx * 2 + 1] = 1;
a.coefs[xx] = 1 << kPrecBits; // 2^21 + v*2^22 >> 22 == v
xo += a0; // iterative, like ImagingScaleAffine
}Verification
check.py generates images, resizes with ./app and compares against
PIL.Image.resize() for every filter across 20 cases (up/down/axis-only,
2048→16 and 16→2048, odd sizes, 1×1, aspect changes, grayscale):
120 pass, 0 fail (ALL BIT-EXACT vs PIL)compare.py writes a side-by-side of source, PIL output, GPU output and
the amplified diff — all diff tiles are black.
Performance
RADV/Renoir iGPU, 6000×4000 → 1500×1000 (24 MP → 1.5 MP), end-to-end including the 72 MB upload and readback:
| filter | GPU total | of which dispatch | PIL |
|---|---|---|---|
| nearest | 39 ms | ~4 ms | 4 ms |
| bilinear | 48 ms | ~12 ms | 168 ms |
| lanczos | 63 ms | ~29 ms | 397 ms |
The standalone CLI path is memcpy-bound — 24 MB of the 39–63 ms is just uploading the image. Where this pays off is a fused GPU pipeline: chained after the GPU JPEG decoder or before a GPU encoder, there is no transfer at all and the dispatch cost (4–29 ms) is the whole story — 6–14× faster than Pillow.
Practical notes
- 8-bit intermediate matters: if you keep 16-bit between passes you get different pixels than Pillow, not “better” ones.
- Coefficient tables scale with output width × kernel size; for a 1500 px output and lanczos (13 taps) that’s ~78 KB — trivial.
- The kernel evaluation and normalization must happen on the host in
double. Reproducing
sin,cosand the normalization in GLSL reintroduces platform-dependent rounding.
The pixel-format conversions that typically surround a resize (RGB↔RGBA, YCbCr, grayscale) can also run on the GPU, bit-exact vs Pillow — see How to convert pixel formats in a Vulkan compute shader.