DEV Community

Jay
Jay

Posted on Edited on

Pillow resizes a cutout by coverage and blurs it by channel, same file

A cutout is a straight-alpha file. It stores colour and coverage separately, and where coverage is zero the colour is still there — whatever the exporter happened to leave in it. Two exports of the same mask from the same model:

rembg_u2net.png        a=0 pixels hold (0, 0, 0)          pure black
rembgstraight_u2net    a=0 pixels hold (218, 218, 218)    the original backdrop
Enter fullscreen mode Exit fullscreen mode

Neither is visible, both are in the file, and they are 218 levels apart. I expected that to be the whole problem: any operation that averages RGB without weighting by coverage would drag that invisible colour into the edge, and my previous article on resampling spaces had already primed me to expect every implementation to do exactly that.

I was wrong about who does it. Not wrong that it happens.

A one-pixel probe

The probe needs no reference image. Take a patch that is half opaque red and half fully transparent, and force it into one pixel. If the operation weights colour by coverage the result is red, because the invisible half contributed nothing:

weighted      (255, 0, 0)
unweighted    (127, 0, 127)
Enter fullscreen mode Exit fullscreen mode

Nothing in between is possible, so one pixel settles the question. My first version of this probe used a 2×2 target, put the boundary on the subsample grid, and every operation came back red — including the ones that are not weighted, because an output pixel that covers two source pixels from the same side never mixes at all. If a measurement says everything agrees, suspect the sampling before believing the result.

A single pixel is still fragile, though, for a different reason: rotate and transform sample points rather than average regions, so a probe pixel can land entirely on the opaque side and come back red along a path that never weights anything. So the test I trust is not one reading but invariance. Run the operation twice on the same patch, changing only the colour under zero coverage — blue the first time, green the second. A weighted path cannot tell the difference, because both colours get multiplied by zero. An unweighted path must, because both are averaged in at full strength.

On Pillow 13.0.0:

operation did the invisible colour change the result? verdict
resize with BOX, BILINEAR, BICUBIC, LANCZOS no weighted
reduce(64), thumbnail(1, 1) no weighted
rotate 45 bilinear, transform AFFINE no weighted
resize with NEAREST n/a — picks a pixel, never mixes no averaging
GaussianBlur(8) yes, by 255 levels unweighted
BoxBlur(8) yes, by 255 levels unweighted

and the reading at the single pixel, for the same patch with a blue filler:

operation result
resize, BOX / BILINEAR / BICUBIC 255, 0, 0, 128
resize, LANCZOS 255, 0, 0, 127
reduce(64), thumbnail(1, 1) 255, 0, 0, 128
rotate 45, transform AFFINE 255, 0, 0, 127
GaussianBlur(8) 122, 0, 133, 122
BoxBlur(8) 120, 0, 135, 120
numpy mean over all channels 127.5, 0, 127.5, 127.5

Every geometric path in the library is weighted. Every blur filter is not. resize with any of its four averaging filters, plus reduce, thumbnail, rotate and transform, all premultiply before they average — and the two spatial filters, the ones you reach for when you want a soft shadow or a feathered edge, convolve each channel on its own.

That is not a version artefact. Pillow 10.4.0, installed side by side, returns 255, 0, 0, 128 from resize and 122, 0, 133, 122 from the same blur. The split has been in the library across at least three minor releases, and it is invisible from the outside: both calls accept the same RGBA image, neither raises, and the resize being correct actively misleads you about the blur.

rotate 90 is missing from the table on purpose. A quarter turn is exact — it moves pixels and never interpolates — so it cannot answer a question about weighted averaging. Forty-five degrees can, and does.

Eleven operations on one RGBA file, sorted by whether changing the colour under zero coverage changes the result: every geometric path says no, both blur filters say yes by 255 levels

Why the blur is the odd one out

A resize is defined as a weighted sum over a neighbourhood, and if you multiply the colours by coverage first, the sum carries the coverage with it. Nobody had to add a special case: premultiplying before the sum is the mathematically complete version, and unpremultiplying is bookkeeping.

A blur is the same operation, so the same argument applies, but there is a detail that makes it easy to get wrong in a different way. Convolution is linear, and coverage is a separate channel that gets convolved too. If you convolve the colour planes alone, the result is a weighted average of colours using the kernel's weights — but the correct answer is a weighted average of colours using the kernel's weights times coverage. Those are different sums, and the difference is exactly the invisible colour, in proportion to how much the kernel reached into transparent territory.

Writing it out, for one output pixel with kernel weights w over neighbours i:

straight      C_out = Σ w_i · C_i
weighted      C_out = Σ w_i · a_i · C_i  /  Σ w_i · a_i
Enter fullscreen mode Exit fullscreen mode

The second one is what you get by premultiplying, blurring, and dividing by the blurred alpha — and the divide is where the 8-bit cost lives.

What it costs on a real file

Two exports of one mask, blurred with radius 2 and downscaled 2×, composited over white, compared against a float64 reference that premultiplies, blurs each plane, averages and composites with no 8-bit intermediate anywhere. Graded over the band where coverage is partial — 2,609 pixels after the resize:

export colour under a=0 edge mean edge max whole-frame mean shift
rembgstraight_u2net.png 218, 218, 218 2.57 12.37 0.091
rembg_u2net.png 0, 0, 0 13.16 29.0 0.234

Same mask. Same radius. Same resize. The only difference is what the exporter left in the pixels nobody can see, and it is worth a factor of 5.1 in edge error.

Two cross-checks on those numbers. A blur written by hand over the same file, doing nothing but convolving each channel with the same kernel, lands on 2.67 and 13.51 — within 0.1 and 0.4 levels of what Pillow returns, which is how I know the library is on the straight-alpha side rather than doing something merely similar. And the reference itself is the float64 pipeline, so neither column is graded against a choice I made in code.

The direction is predictable once you see it: black filler pulls the edge darker, and a light filler barely moves it because 218 is close to the white you are compositing onto. This is why the bug survives review. If your cutouts come out of a pipeline that fills transparent pixels with white — which is what you get from masking a white studio background — a blur that ignores coverage produces something very close to correct, and you conclude the blur is fine.

Widening the kernel makes it worse and then stops making it worse, on the grey export:

blur radius edge mean edge max
0.5 0.52 5.05
1 1.19 8.58
2 2.67 13.12
4 4.53 17.18
8 5.63 18.48

The curve rises and then flattens rather than tracking radius. I did not isolate why. The plausible explanation is that past radius 4 most of the kernel already sits over fully transparent pixels, so reaching further adds little new colour — but that is an inference from the shape, not a measurement, and the flattening is not evidence that anything is getting better.

Note the whole-frame mean column: 0.09 and 0.23 levels. This is the same shape as the space error from the earlier article — a defect that is tens of levels wide on the edge and invisible in any statistic computed over the frame. A per-image metric will never fire on it.

Edge error of a straight-alpha blur on two exports of one mask, 2.57 against 13.16 levels, and the same error as blur radius grows from 0.5 to 8

The fix, and what it costs

Premultiply once, do everything, and only divide back out at the moment you composite:

import numpy as np
from PIL import Image, ImageFilter


def premultiply(im):
    a = np.asarray(im.convert("RGBA"), dtype=np.float64)
    out = a.copy()
    out[:, :, :3] = np.round(a[:, :, :3] * (a[:, :, 3:4] / 255.0))
    return Image.fromarray(np.clip(out, 0, 255).astype(np.uint8))


def blur_cutout(im, radius):
    """Blur with coverage as a weight, and stay premultiplied."""
    return premultiply(im).filter(ImageFilter.GaussianBlur(radius))


def over_white(pm):
    """Composite premultiplied RGBA over white: no division needed."""
    a = np.asarray(pm, dtype=np.float64)
    return a[:, :, :3] + 255.0 * (1.0 - a[:, :, 3:4] / 255.0)
Enter fullscreen mode Exit fullscreen mode

Staying premultiplied is not laziness. Dividing by alpha and multiplying back is a round trip through 8 bits, and it is lossy in exactly the region this article is about — low coverage. Worst case over all 256 colour levels at a given coverage:

coverage alpha worst round-trip error
255 1.000 0
128 0.502 1
64 0.251 2
32 0.126 4
16 0.063 8
8 0.031 16
4 0.016 32
2 0.008 64
1 0.004 127

At the lowest coverages the round trip destroys the colour entirely — a level of 127 comes back as 0, because 127 × 1/255 rounds to zero and dividing zero gives zero. Those are the pixels just outside the silhouette, the ones the blur was supposed to feather. So the correct pipeline is not "premultiply, do the work, unpremultiply" — it is "premultiply, do the work, and keep it premultiplied until the composite, where the division never has to happen."

That also means you cannot hand the intermediate back to code that expects straight alpha, which is the real cost: it changes the interface of everything downstream, not just one call.

Two pipelines side by side, straight alpha against premultiplied, and the worst 8-bit round-trip error by coverage rising to 127 levels at coverage 1

Checking the tools

The same probe against the other implementations on this machine, all of which are weighted:

path result
sips (CoreGraphics) 255, 0, 0, 128
Chrome canvas, drawImage, high quality 255, 0, 0, 127
Pillow 10.4.0 resize 255, 0, 0, 128
Pillow 13.0.0 resize 255, 0, 0, 128

So the geometric side of the world agrees, and has for a while. The blur side is where a file that looks the same to every viewer gets treated two different ways depending on which function you happened to call.


I work on PicViva, and this one bit me during a shadow pass. A softened contact shadow is a blur of the matte before it is composited, and the pipeline had the blur on the straight file with the resize pointed at the same array — one of those operations was correct and the other was quietly pulling the old backdrop into the rim. The reason it took a while to find is the same reason it is worth writing down: the resize was right, so the file looked honest, and the only thing wrong was the step next to it.

The fix lives in our background removal path, where the matte is already premultiplied before anything touches it, so every downstream step inherits the weighting instead of having to remember it.

If you want the neighbouring case — a resample that is wrong in the same space for every kernel, at 60 levels rather than 13 — that one is here: a 1 px checkerboard downscales to 128, and half its light is 188.

Top comments (0)