matlab - Not showing foreground in smooth transitions

I would like to achieve image blending with smooth transitions using alpha blending using and smoothed mask. I used Gaussian filter for the mask and now I'm trying to combine the other two images. I'm using the smoothed mask as a weight.

x_i and y_i .... color information for pixel i

alpha_i ... value of the mask in pixel i

formula: z_i = alpha_i*x_i + (1 - alpha_i)*y_i

My attempt:

mask = imread('mask.png');
foreground = imread('fg.jpg');
background = imread('bg.jpg');
[r,c,~]=size(mask);
A = zeros(size(foreground),'like', foreground);
fspe = fspecial('gaussian', 100);  
smoothMask = imfilter(double(mask), fspe, 'same'); 
for i=1:r 
  for j=1:c       
    for d=1:3            
      alpha = mask(i,j,d);
      A(i,j,d) = alpha*foreground(i,j,d)+(1-alpha)*background(i,j,d);           
    end    
  end
end
imshow(A);

In the end I get the background but the foreground is white. Please help.

1 Answer

  1. Albert- Reply

    2019-11-13

    Your A is of type double and in range [0..255]. When imshowing images of type double the expected scale is [0..1] this is why all pixels are shown saturated.

    Fix:

    imshow(A,[])
    

    Or

    imshow(A/255)
    

    A word about : In Matlab it is quite redundant to explicitly loop through all rows columns and channels just to multiply and sum images (3D arrays). It can be easily done

    A = mask.*foreground + (1-mask).*background;
    

    Isn't it lovely?

    Note the difference between * operator and .* operator - it's the difference between matrix multiplication and element-wise multiplication.

Leave a Reply

Your email address will not be published. Required fields are marked *

You can use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>