function m010
	%m010: Resta dos imagenes capturadas desde la Webcam y aplica mascara
	%requiere los archivos vfm.dll y vfm.m

   vfm('show',0);%hide %vfm('preview',1);%on
   vfm('grab',1);
	Original=double(vfm('grab',1));
   Original=(Original(:,:,1)+Original(:,:,2)+Original(:,:,3))/3;
	[nf nc]=size(Original);   
   subplot(2,2,1);imshow(Original,[]);title('Primera imagen');	     
   f1=round(nf-nf/4);
   f2=round(nf+nf/4);
   c1=round(nc-nc/4);
   c2=round(nc+nc/4);
      
   mask=zeros(nf,nc);
   for f=f1:f2
      for c=c1:c2
         mask(f,c)=1;
      end;
   end;
   subplot(2,2,3);imshow(mask,[]);title('Mask');
   
   
 for it=1:20  
   
   disp('Presione una tecla para capturar la primera imagen...');pause;
   
   vfm('grab',1);
	Original=double(vfm('grab',1));
   Original=(Original(:,:,1)+Original(:,:,2)+Original(:,:,3))/3;
   subplot(2,2,1);imshow(Original,[]);title('Primera imagen');	
   
   vfm('grab',1);
	Captura=double(vfm('grab',1));
   Captura=(Captura(:,:,1)+Captura(:,:,2)+Captura(:,:,3))/3;
   subplot(2,2,2);imshow(Captura,[]);title('Segunda imagen');

   IMResta=Resta(Original,Captura);
	IMResta=Mascara(IMResta,Mask);

	s=Suma(IMResta);
   subplot(2,2,4);imshow(IMResta,[]);title('Resta entre las imagenes 1 y 2');
   
   if s>1000,
      disp('ALARMA!!!!');
   else
      disp('ok');
   end;
   
end;


function IM3=Resta(IM1,IM2)

	[nf nc]=size(IM1);
	IM3=zeros(nf,nc);
	for f=1:nf
      for c=1:nc
         IM3(f,c)=abs(IM2(f,c)-IM1(f,c));
	   end;
	end;
      
   
function s=Suma(IM)
   %en matlab==> s=sum(sum(IM)); 
	[nf nc]=size(IM);
	s=0;
	for f=1:nf
      for c=1:nc
         s=s+IM(f,c);
	   end;
	end;
   
function IM2=Mascara(IM,Mask)
   %en matlab==> IM2=IM.*Mask; 
   [nf nc]=size(IM);
   IM2=zeros(nf,nc);
	for f=1:nf
      for c=1:nc
         IM2(f,c)=IM(f,c)*Mask(f,c);
	   end;
	end;
