imblend.m 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. function [ imageO, alphaO ] = imblend ( imageA, alphaA, imageB, alphaB )
  2. %IMBLEND Combine image A and B with alpha channels
  3. % Usage:
  4. % [ X ] = imblend ( imageA, alphaA, imageB, alphaB )
  5. % Input:
  6. % imageA, imageB = MxNx3 CDATA
  7. % alphaA, alphaB = scalar or MxN alpha map
  8. % imageA in front, imageB in the back
  9. % Output:
  10. % X = X
  11. %
  12. % See also imagescX
  13. %
  14. % Copyleft 1999-, XMO.
  15. % check input
  16. if any(alphaA(:) < 0) || any(alphaA(:) > 1) || any(alphaB(:) < 0) || any(alphaB(:) > 1)
  17. error('alpha should be within [0 1]');
  18. end
  19. if size(imageA, 3) ~= 3 && size(imageB, 3) ~= 3
  20. error('unknown input image format');
  21. end
  22. if size(imageA) ~= size(imageB)
  23. error('image dimension mismatch');
  24. end
  25. if isscalar(alphaA)
  26. elseif size(alphaA, 1) == size(imageA, 1) && size(alphaA, 2) == size(imageA, 2) && size(alphaA, 3) == 1
  27. else
  28. error('inappropriate alphaA');
  29. end
  30. if isscalar(alphaB)
  31. elseif size(alphaB, 1) == size(imageB, 1) && size(alphaB, 2) == size(imageB, 2) && size(alphaB, 3) == 1
  32. else
  33. error('inappropriate alphaB');
  34. end
  35. % return directly if completely transparent
  36. if all(alphaA(:) == 0) && all(alphaB(:) == 0)
  37. imageO = zeros(size(imageA));
  38. return;
  39. end
  40. % calculate alpha
  41. alphaO = alphaA + alphaB .* (1 - alphaA);
  42. % calculate image
  43. imageO = zeros(size(imageA), class(imageA));
  44. for i = 1:3
  45. imageO(:,:,i) = (imageA(:,:,i) .* alphaA + imageB(:,:,i) .* alphaB .* (1 - alphaA)) ./ alphaO;
  46. end