I'm writing a simple box blur for a graphics library. The formula makes the average of a range of pixels by adding the ARGB amounts and then dividing by the blur range

For example, with a blur range of 3;

pixel1 FF FF 00 00 +
pixel2 FF 00 FF 00 +
pixel3 FF 00 00 FF
/ 3 =
result FF 55 55 55

Which is correct. A typical result shows as;

enter image description here

However, I am having difficulty with coming up with a formula to blur an image with alpha transparency. The formula above gives this result for a yellow box on a transparent background;

enter image description here

You can see that the yellow is surrounded by black colour - because the red and green are being diminished to 0. The result should actually look like so;

enter image description here

So; the formula of (pixel + pixel + pixel) / range is not working for alpha-blended images.

Can anyone please give a correct formula?



Two suggestions:

  1. If your data is from an image you are displaying on a standard monitor, the chances are it is (or you are implicitly assuming that it's) in sRGB format. This means that the colour components are not linear. Ideally, you should first map into a linear colour space, do your filtering (e.g. blurring) operations, and then map back.
    *(If you just want to try a cheap and cheerful approach, squaring each of the R G B components is not a terrible approach to "linearise" the values

    • obviously, use sqrt() to map back)*.
      The alpha channel can be assumed to be linear.
  2. Once in linear colour space, the next thing you want to do before filtering is to convert the pixels to a pre-multiplied-alpha format (AKA "associated colour").
    Basically, given 8bpc {A,R,G,B} pixel input, produce {A, A*R/255, A*G/255, A*B/255}. You then do your averaging on this premultiplied data as above on all four channels, and then map back by dividing through by the resulting alpha (if A=0 then, choose, RGB=0).

This should produce a better result. For more info I suggest reading through Jim Blinn's "Compositing, Part1: Theory".
Particularly, note the line "Additionally, we must use associated colors for any filtering or interpolation operations"

Update: Seems I've posted a similar answer before


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.