1
votes

I'm trying to implement image convolution with a 3x3 matrix, where my colour components (each ranging from 0 to 255) are stored using pre-multiplied alpha. All the tutorials (e.g. http://www.codeproject.com/KB/GDI-plus/csharpfilters.aspx) I can find only describe performing the convolution calculations on the RGB components and nothing is mentioned about the alpha component.

My current code leaves the alpha component as it is. The filters I have tried look fine when working on images where every pixel already has full alpha set. When I have partially transparent pixels e.g. a boxblur filter looks strange because pixel colors do not propagate into transparent areas when blurring happens.

What calculations do I perform on the alpha component when running the convolution algorithm and how do I deal with pre-multiplied alphas when setting the final pixel value? Also, do I add the filter offset to the alpha component?

I've tried calculating my new alpha component the same way I calculate the RGB components (i.e. adding up the surrounding alpha values for that pixel according to the filter matrix) but I get colored fringes appearing on the edge of transparent areas and semi-transparent pixels start to darken too much. I think I need to change the new RGB components to take into account the new alpha value but I'm not sure what to do.

Thanks.

1

1 Answers

2
votes

I think that the correct way is to first compute just the alpha of the convolution using the standard formulas

alpha = a1*m1 + a2*m2 + a3*m3 +
        a4*m4 + a5*m5 + a6*m6 +
        a7*m7 + a8*m8 + a9*m9;

then you must compute the convolution of the original (non-premultiplied) r/g/b and post-multiply by alpha

red = (r1/a1*m1 + r2/a2*m2 + r3/a3*m3 +
       r4/a4*m4 + r5/a5*m5 + r6/a6*m6 +
       r7/a7*m7 + r8/a8*m8 + r9/a9*m9) * alpha;

with a similar formula for green and blue.

A more efficient way would be first removing premultiplication (i.e. replacing r with r/a, g with g/a and b with b/a) doing the convolution of all components using standard formulas and then re-premultiply (replacing r with r*a, g with g*a and b with b*a).