% webcam_segmentation
%
% small demo opening live image stream from webcam. Grabs initial
% image as reference image, performs mean filtering 
% and segments live-stream by difference image and thresholding

% Bernard Haasdonk 31.7.2007

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% general setting that may be changed
pa = 0.1;      % pause-length after each plot
mean_filter_size = 9; % 1 = no filter
segmentation_threshold = 5; % greyvalue-difference for segmentation
show_step = 4; % 0 == unfiltered live stream
               % 1 == filtered live stream
	       % 2 == difference image
	       % 3 == segmentation by thresholding
	       % 4 == segmented original

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
disp('please klick on the window to exit');
f = figure;
set(f,'doublebuffer','on'); 
set(f,'Name','Tolles Webcam Tool')

a = vcapg2(0);

set(f,'WindowButtonDownFcn','set(gcbf,''Userdata'',1);');
set(f,'WindowButtonUpFcn','set(gcbf,''Userdata'',0);');
set(f,'Userdata',0);

filter_kernel = ones(mean_filter_size, mean_filter_size)/ mean_filter_size^2;

% get background image and filter
b = vcapg2;
db = double(b);  
db = mean(db,3);
db2 = filter2(filter_kernel, db);

while 1~=0
  % get livestream image and filter
  a = vcapg2;
  da = double(a);  
  da = mean(da,3);
  da2 = filter2(filter_kernel, da);

  % difference image
  dc = abs(db2-da2);
  
  % thresholded difference image
  dd = (dc > segmentation_threshold)*255; 
  
  if show_step == 0
    df = da;
  end;
  if show_step ==1 
    df = da2;
  end;
  if show_step ==2
    df = dc;
  end;
  if show_step == 3
    df = dd;
  end;
  if show_step == 4
    df = da .* (dd/255);
  end;
  
  imshow(uint8(df)); 
  pause(pa);  
  drawnow; 
  
  % check if button is pressed for exit or not.
  mousebutton = get(f,'Userdata');
  if mousebutton
    close(f);
    disp('Goodbye!');
    return;
  else
    pause(pa);
  end;
  
end

