Blurring a semi-transparent image

Alec Jacobson

February 10, 2014

weblog/

My brain paused a moment today trying to think how I can correctly blur an RGBA image (a color image with an alpha channel encoding transparency or rather opacity). Assuming you have an image in X and an alpha-map in A here's a small matlab script demonstrating how to premultiply and then unpremultiply to get the correct output image Y and output alpha map B.

% blur kernel
H = fspecial('gaussian',100,100);
% pre-multiply
XA = bsxfun(@times,X,A);
% Apply blur to pre-multiplied image
XAH = imfilter(XA,H,'replicate');
% Apply blur to alpha mask
B = imfilter(A,H,'replicate');
% _Un_-pre-multiply by blurred mask (plus eps to avoid divide by zero
Y = bsxfun(@rdivide,XAH,B+(B==0)*eps);
% Checkerboard background function
checker = @(im,A) bsxfun(@times,1-A,repmat(1-0.2*xor((mod(repmat(0:size(im,2)-1,size(im,1),1),8*2)>7),(mod(repmat((0:size(im,1)-1)',1,size(im,2)),8*2)>7)),[1 1 3])) + bsxfun(@times,A,im);
% Show result
imshow([ ...
  X repmat(A,[1 1 3]); ...
  checker(X,A) XA; ...
  XAH repmat(B,[1 1 3]); ...
  Y checker(Y,B)])

matlab blur transparent image

Source Source