File: ef230-2023-08/www/examples/image_transparency.m Download
%| Image transparency example
%| Shows how to use and make a transparency matrix with an image
%  University of Tennessee : EF 230 Spring, 2012 : Will Schleter


function main
close all;
% read the image with transparency data
[img,cm,alpha] = imread('http://upload.wikimedia.org/wikipedia/commons/b/bc/Gluecksklee_(transparent_background).png');

if isempty(alpha)
    warning('Image does not have transparency data')
end

% show the image
image([0 100],[0 100],img,'alphadata',alpha)

% show another (smaller version)
hold on
image([50 100],[50 100],img,'alphadata',alpha)

% try out a custom routine for getting background
aa = getalpha(img);
image([0 50],[0 50],img,'alphadata',aa)

% and again, with a tolerance
rgb = [118,232,184];
bb = getalpha(img,rgb-75,rgb+75);
image([0 50],[50 100],img,'alphadata',bb)

end % main


function a = getalpha(img,rgb1,rgb2)
%PURPOSE
% Generate an alpha map for an image based on a range of rgb
% values
%
%INPUT
% img - truecolor image
% rgb1 - optional lower rgb value (defaults to color of default left pixel)
% rgb2 - optional upper rgb value (defaults to rgb1)
%
%OUTPUT
% a - uint8 alpha map with 255 representing transparent pixels

if nargin==0
    error('Must supply an input image')
end
if nargin==1
    rgb1 = img(1,1,:) % set bottom limit to be color of top left pixel
end
if nargin<=2
    rgb2=rgb1 % set top limit to be the same as the bottom
end

[nr,nc,ncol] = size(img);
if ncol==1
    error('Image must be a true color image');
end
a = uint8(ones(nr,nc))*255;

ai = find( img(:,:,1)>=rgb1(1) & img(:,:,2)<=rgb2(2) & ...
           img(:,:,2)>=rgb1(2) & img(:,:,2)<=rgb2(2) & ...
           img(:,:,3)>=rgb1(3) & img(:,:,3)<=rgb2(3) );
a(ai)=0;
end % getalpha