function varargout = guip(varargin)
% GUIP M-file for guip.fig
%      GUIP, by itself, creates a new GUIP or raises the existing
%      singleton*.
%
%      H = GUIP returns the handle to a new GUIP or the handle to
%      the existing singleton*.
%
%      GUIP('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in GUIP.M with the given input arguments.
%
%      GUIP('Property','Value',...) creates a new GUIP or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before guip_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to guip_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools open.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help guip

% Last Modified by GUIDE v2.5 24-Oct-2012 13:50:32

% Begin initialization code - DO NOT EDIT

gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @guip_OpeningFcn, ...
                   'gui_OutputFcn',  @guip_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);

if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end

               
% End initialization code - DO NOT EDIT


% --- Executes just before guip is made visible.
function guip_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to guip (see VARARGIN)



   [a,map]=imread('play.jpg');
  [r,c,d]=size(a);
  x=ceil(r/50);
  y=ceil(c/60);
  g=a(1:x:end,1:y:end,:); g(g==255)=5.5*255;
  set(handles.play,'CData',g);
  handles.output = hObject;
 
  [b,map2]=imread('stop.jpg');
  [r2,c2,d2]=size(b);
  x2=ceil(r2/50);
  y2=ceil(c2/60);
  g2=b(1:x2:end,1:y2:end,:); g2(g2==255)=5.5*255;
  set(handles.stop,'CData',g2);
  handles.output = hObject;
  
  [c,map3]=imread('abrir.jpg');
  [r3,c3,d3]=size(c);
  x3=ceil(r3/28);
  y3=ceil(c3/28);
  g3=c(1:x3:end,1:y3:end,:); g3(g3==255)=5.5*255;
  set(handles.abrir,'CData',g3);
  handles.output = hObject;
  
  [d,map4]=imread('procesar.jpg');
  [r4,c4,d4]=size(d);
  x4=ceil(r4/32);
  y4=ceil(c4/32);
  g4=d(1:x4:end,1:y4:end,:); g4(g4==255)=5.5*255;
  set(handles.pushbutton5,'CData',g4);
  handles.output = hObject;

% Choose default command line output for guip



% Update handles structure
guidata(hObject, handles);

% UIWAIT makes guip wait for user response (see UIRESUME)
% uiwait(handles.figure1);

  




% --- Outputs from this function are returned to the command line.
function varargout = guip_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure




% --- Executes on button press in play.
function play_Callback(hObject, eventdata, handles)
% hObject    handle to play (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


global parar

i=1;
parar=0;
imagen_video=handles.img;
A=get (imagen_video);
frames=A.NumberOfFrames;



         while(i<=frames)
              
             if parar==1 
                                 
                 clear all
          break; 
            end

        imagencolor2=read(imagen_video,i+20);
        
        axes(handles.axes2)
        imshow(imagencolor2) 
        axis off
        i=i+1;
         end




% --- Executes on button press in stop.
function stop_Callback(hObject, eventdata, handles)
% hObject    handle to stop (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global parar
parar = 1;




% --- Executes on button press in abrir.
function abrir_Callback(hObject, eventdata, handles)
% hObject    handle to abrir (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


global imagen_video
global nombre
global imagencolor



%makemid
[nombre dire]=uigetfile('*.*','Abrir');
if nombre==0
    return
end
imagen_video=mmreader(fullfile(dire,nombre));
imagencolor=read(imagen_video,1);
axes(handles.axes2)
axis off

imshow(imagencolor)
axis off
handles.img=imagen_video;
guidata(hObject,handles);

A1=get (imagen_video);
frames1=A1.NumberOfFrames;

        set(handles.frameini,'String',num2str(1));
        set(handles.framefin,'String',num2str(frames1));
        set(handles.text9,'String',num2str(1));


    

% --- Executes on key press with focus on abrir and none of its controls.
function abrir_KeyPressFcn(hObject, eventdata, handles)
% hObject    handle to abrir (see GCBO)
% eventdata  structure with the following fields (see UICONTROL)
%	Key: name of the key that was pressed, in lower case
%	Character: character interpretation of the key(s) that was pressed
%	Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles    structure with handles and user data (see GUIDATA)





% --- Executes on button press in procesar.
function procesar_Callback(hObject, eventdata, handles)

% hObject    handle to pushbutton5 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

global parar
global seleccion
global imagencolor2
global umbral
global bw
global retardo
global frameini
global framefin
global imagen_patron
global imagen_resta
global imagen_video
global area_minima


seleccion=1;
parar=0;
imagen_video=handles.img;
A=get (imagen_video);
frames=A.NumberOfFrames;
area3=0;
areas=zeros(1,frames); %Inicializamos areas, ceros en todos los frames del video


f=1;
   


 
 if isempty(imagen_patron)==1
     
     imagen_patron=20;
     set(handles.nframes,'String',num2str(imagen_patron));
     imagen_patron=20;
     
 end
if isempty(retardo)==1
    
    retardo=1;
    set(handles.retardo,'String',num2str(retardo));
    
end
if isempty(frameini)==1
    
    frameini=imagen_patron+1;
    set(handles.frameini,'String',num2str(frameini));
end

i=frameini;

if isempty(framefin)==1
    framefin=frames;
    set(handles.framefin,'String',num2str(framefin));
end

if isempty(area_minima)==1
    area_minima=80;
end



%--------------------------------------------------------------------------
%--Empezamos el procesamiento de detección de humo.
%--------------------------------------------------------------------------

         while(i<=framefin-imagen_patron)
             
       
            if parar==1 
                                                  
                break; 
                clear all
            end
            
            


%--------------------------------------------------------------------------
%--Visualizamos el frame actual.
%--------------------------------------------------------------------------

set(handles.text9,'String',num2str(i));

%--------------------------------------------------------------------------

     tic;


     
%--------------------------------------------------------------------------
%--Calculamos a partir de la imagen patrón y el siguiente frame, la resta 
%--de ambas para ver lo que ha cambiado en la imagen de una
%--a otra. Esta resta la convertimos a una imagen binaria y la mostramos.
%--------------------------------------------------------------------------

        imagencolor=read(imagen_video,imagen_patron);
        
        imagencolor2=read(imagen_video,i+imagen_patron);
        handles.im2=imagencolor2;
        guidata(hObject,handles);
        
        imagen_double = im2double(imagencolor);
        imagen_double2 = im2double(imagencolor2);
      
        imagen_resta=imagen_double2-imagen_double;
        imagen_resta=abs(imagen_resta);
      
 %--------------------------------------------------------------------------
%--Bucle para: si estamos en la primera pasada del programa, que detecte si
%--el usuario a escrito un valor en umbral o no. Si lo ha escrito el valor
%--permanece constante dusrante todo el proceso. Si el usuario no lo ha
%--escrito, cada pasada calcularemos un umbral óptimo de forma automática
%--con la función grayhresh.
%--------------------------------------------------------------------------


        if i==frameini
            if isempty(umbral)==1
            
                umbral =graythresh(imagen_resta);
                
                set(handles.umbral,'String',umbral);
                usuario=0;
               
            else
                usuario=1;
                umbral = get(handles.umbral,'String');
                umbral=str2num(umbral);
               
            end
        else
            if usuario==0
                
                umbral =graythresh(imagen_resta);
                set(handles.umbral,'String',umbral);
                
            end
        end            

     histograma_Callback(hObject, eventdata, handles)   
%--------------------------------------------------------------------------       
    
         bw=im2bw(imagen_resta,umbral);
        
        handles.bw=bw;
        axes(handles.axes6)  %mostramos la diferencia de imagenes en binario
        imshow(bw)
        axis off 
        
%--------------------------------------------------------------------------
 

 
          se = strel('disk',1);        
          dilateBW = imdilate(bw,se);
          bw = imerode(dilateBW,se); %erosionamos pequeños objetos en forma de disco
   
          handles.bw=bw;
          guidata(hObject,handles);
         
         
%--------------------------------------------------------------------------
%-- Eliminamos todos los pequeños objetos no deseados con la operación open: erode
%--dilate. Los eliminamos en forma de disco para conseguir imitar la forma
%--redondeada del humo.
%--------------------------------------------------------------------------
        
         se = strel('disk',4);        
         
         erodedBW = imerode(bw,se); 
         bw_fin = imdilate(erodedBW,se);
         handles.bw=bw_fin;
         guidata(hObject,handles);
        
         
%--------------------------------------------------------------------------
        
%--------------------------------------------------------------------------
%--Esta operación es necesaria ya que aun haciendo la operación open para
%--eliminar pequeños objetos no deseados, siguen habiendo reginones que no 
%--nos conviene tener.
%--------------------------------------------------------------------------


          [L,num] = bwlabel(bw_fin); %devuelve en NUM el numero de objetos
          %conectados encontrados en bw
    
          s  = regionprops(L,'all'); %propiedades de los objetos
         
           bw3= ismember(L, find([s.Area] >= area_minima));
           handles.bw3=bw3;
          axes(handles.axes7)
          axis off
          imshow(bw3) 
%--------------------------------------------------------------------------






%--------------------------------------------------------------------------
%-- Contorneamos el humo sobre la imagen original.
%--------------------------------------------------------------------------
          
          axes(handles.axes1)
          imshow(imagencolor2)
          hold on
          imcontour(bw3,1,'b');
          


% 
              [K3,n3] = bwlabel(bw3);
              s3  = regionprops(K3,'all');
%             
%              
              for j=1:n3
                 area3(j)=s3(j).Area;
              end
%             
              areas(f)=sum(area3);
%              
%            

        
          
      i=i+retardo;
       f=f+1;
%       



 %-------------------------------------------------------------------------
 %--Repreoducimos el video original en la primera ventana.
 %-------------------------------------------------------------------------
               axes(handles.axes2)
               imshow(imagencolor2) 
               axis off

%--------------------------------------------------------------------------
              
   
          end   % del while

          
     areas=areas(1:f);

%             
     axes(handles.axes2)
     axis off
     hold on
     plot (areas,'b');
   

 guidata(hObject,handles);
    








function umbral_Callback(hObject, eventdata, handles)
% hObject    handle to umbral (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of umbral as text
%        str2double(get(hObject,'String')) returns contents of umbral as a double

global umbral

umbral= get(handles.umbral,'string');
umbral=str2num(umbral);






function frameini_Callback(hObject, eventdata, handles)
% hObject    handle to frameini (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of frameini as text
%        str2double(get(hObject,'String')) returns contents of frameini as a double

global frameini

frameini= get(handles.frameini,'string');
frameini=str2num(frameini);



% --- Executes during object creation, after setting all properties.
function frameini_CreateFcn(hObject, eventdata, handles)
% hObject    handle to frameini (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function framefin_Callback(hObject, eventdata, handles)
% hObject    handle to framefin (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of framefin as text
%        str2double(get(hObject,'String')) returns contents of framefin as a double

global framefin

framefin= get(handles.framefin,'string');
framefin=str2num(framefin);


% --- Executes during object creation, after setting all properties.
function framefin_CreateFcn(hObject, eventdata, handles)
% hObject    handle to framefin (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function retardo_Callback(hObject, eventdata, handles)
    
% hObject    handle to retardo (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of retardo as text
%        str2double(get(hObject,'String')) returns contents of retardo as a double


global retardo

retardo= get(handles.retardo,'string');
retardo=str2num(retardo);






% --- Executes during object creation, after setting all properties.
function retardo_CreateFcn(hObject, eventdata, handles)
% hObject    handle to retardo (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function nframes_Callback(hObject, eventdata, handles)
% hObject    handle to nframes (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of nframes as text
%        str2double(get(hObject,'String')) returns contents of nframes as a double

global imagen_patron

imagen_patron= get(handles.nframes,'String');

 imagen_patron=str2num(imagen_patron);


    
    

%imagen_patron=str2num(imagen_patron);



% --- Executes during object creation, after setting all properties.
function nframes_CreateFcn(hObject, eventdata, handles)
% hObject    handle to nframes (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes during object creation, after setting all properties.
function umbral_CreateFcn(hObject, eventdata, handles)
% hObject    handle to umbral (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes during object creation, after setting all properties.
function figure1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called


% --- Executes when user attempts to close figure1.
function figure1_CloseRequestFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: delete(hObject) closes the figure

ans=questdlg('¿Desea salir del programa?','SALIR','Si','No','No');
if strcmp(ans,'No')
return;
end
delete(hObject);
clear,close all
clear all


% --- Executes on selection change in ayuda.
function ayuda_Callback(hObject, eventdata, handles)
% hObject    handle to ayuda (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns ayuda contents as cell array
%        contents{get(hObject,'Value')} returns selected item from ayuda

str = get(hObject, 'String');
val = get(hObject,'Value');

switch str{val};

     case 'Proceso 1'
         msgbox('Imágenes procesadas sin empleo de operaciones morfológicas','Proceso 1','help');
         
     case 'Proceso 2'
         msgbox('Imágenes procesadas tras el empleo de operaciones morfológicas','Proceso 2','help'); 
         
     case 'Proceso 3'
         msgbox('Resultado final tras la detección del humo','Proceso 3','help');
     
end


% --- Executes during object creation, after setting all properties.
function ayuda_CreateFcn(hObject, eventdata, handles)
% hObject    handle to ayuda (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- If Enable == 'on', executes on mouse press in 5 pixel border.
% --- Otherwise, executes on mouse press in 5 pixel border or over play.
function play_ButtonDownFcn(hObject, eventdata, handles)
% hObject    handle to play (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --- Executes on button press in histograma.
function histograma_Callback(hObject, eventdata, handles)
% hObject    handle to histograma (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

global imagen_resta
global umbral

imagen_resta_gray=rgb2gray(imagen_resta);
axes(handles.axes9); 

%hold on
%imhist(imagen_resta_gray);
[a,b]=imhist(imagen_resta_gray);
plot(b,a,'b',umbral.*ones(1,length(a)),b.*max(a),'r')
%plot(umbral.*ones(1,length(a)),b.*max(a),'r')
%hold off


% --- Executes on button press in imagen_patron.
function imagen_patron_Callback(hObject, eventdata, handles)
% hObject    handle to imagen_patron (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

global imagen_video

imagen_patron=get(handles.nframes,'String');
imagen_patron=str2num(imagen_patron);

imagenpatron=read(imagen_video,imagen_patron);
axes(handles.axes9)
imshow(imagenpatron)
axis off

imshow(imagenpatron)


% --------------------------------------------------------------------
function open_Callback(hObject, eventdata, handles)
% hObject    handle to open (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function Untitled_1_Callback(hObject, eventdata, handles)
% hObject    handle to Untitled_1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function Untitled_2_Callback(hObject, eventdata, handles)
% hObject    handle to Untitled_2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function Untitled_4_Callback(hObject, eventdata, handles)
% hObject    handle to Untitled_4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)



function areaminima_Callback(hObject, eventdata, handles)
% hObject    handle to areaminima (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of areaminima as text
%        str2double(get(hObject,'String')) returns contents of areaminima as a double

global area_minima

area_minima=get(handles.areaminima,'String');
area_minima=str2num(area_minima);



% --- Executes during object creation, after setting all properties.
function areaminima_CreateFcn(hObject, eventdata, handles)
% hObject    handle to areaminima (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --------------------------------------------------------------------
function procesado_Callback(hObject, eventdata, handles)
% hObject    handle to procesado (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function helpp_Callback(hObject, eventdata, handles)
% hObject    handle to helpp (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function docu_Callback(hObject, eventdata, handles)
% hObject    handle to docu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function histo_Callback(hObject, eventdata, handles)
% hObject    handle to histo (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function imapatron_Callback(hObject, eventdata, handles)
% hObject    handle to imapatron (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function procesa_Callback(hObject, eventdata, handles)
% hObject    handle to procesa (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
