function [ composite ] = chromakey( subject, background, minKey, maxKey )
%chromakey Composite two images together based on a key color.

% This function returns an image that is a combination of the color
% images in "subject" and "background." Specifically, the result contains
% pixels from "subject" whenever those pixels have colors outside the range
% "minKey" to "maxKey" (inclusive), and pixels from "background" wherever
% colors are in that range.


% Build a 0/1 mask array with as many rows and columns as the subject and
% background images, and a 1 wherever pixels should come from the
% background, 0 where they should come from the subject.

d = size( subject );
wh = d( 1:2 );                  % Width and height of image

minKey = repmat( reshape( minKey, [1 1 3] ), [ wh 1 ] );
maxKey = repmat( reshape( maxKey, [1 1 3] ), [ wh 1 ] );

colorMask = minKey <= subject & subject <= maxKey;
pixelMask = all( colorMask, 3 );
backgroundMask = uint8( repmat( pixelMask, [1 1 3] ) );


% Use the mask to combine subject and background images

composite = subject .* ( 1 - backgroundMask ) + background .* backgroundMask;

end

