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

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

% Last Modified by GUIDE v2.5 07-May-2011 21:53:54

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @GUI_OpeningFcn, ...
                   'gui_OutputFcn',  @GUI_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 GUI is made visible.
function GUI_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 GUI (see VARARGIN)

% Choose default command line output for GUI
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

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


% --- Outputs from this function are returned to the command line.
function varargout = GUI_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
varargout{1} = handles.output;


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


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

o_programu;


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

myVid = uigetfile( ...
{'*.avi;','AVI'; ...    %typy k otevreni; zobrazeni v openboxu
   '*.mpeg',  'MPEG'; ...
   '*.*',  'All Files (*.*)'}, ...      
   'Otevřít video');                  %Popis open boxu

global video;
global cellFrames;
global position;
global loop;
loop = false;

global stop;    %podminka pro zastaveni videa
stop = false;

global counter;     %podminka pro citac
counter = false;


position = cell(1,10);
frames = 100;

video = mmreader(myVid); 
cellFrames = cell(2, frames);       %vytvori prostor pro data
cellFrames{1, 1} = read(video, 1);

set(handles.text7, 'String', 'Video načteno');

set(handles.DetSnimek, 'UserData', 1)

axes(handles.DetSnimek);     %ulozi obraz do axes1
imshow(cellFrames{1,1});


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

konec = questdlg('Opravdu chcete ukončit aplikaci?','Ukončení programu','Ano','Ne','Ano');
switch konec,
   case 'Ano',
   clear all;
   close all;
   case 'Ne'
     return
end

% --- Executes during object creation, after setting all properties.
function vybermodelu_CreateFcn(hObject, eventdata, handles)
% hObject    handle to vybermodelu (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


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

%%%%%%%%%INICIALIZACE
global video;
global cellFrames;
global position;
global val;
global obrazek
global stop;
global counter;

object = str2num(get(handles.objekty, 'String'));
morf = str2num(get(handles.strel, 'String'));

%chybove hlasky
if counter == false
    errordlg('Není aplikován žádný čítač','Chyba programu');
elseif get(handles.DetSnimek, 'UserData') == 0
    errordlg('Není načteno video','Chyba programu');
else

set(handles.text7, 'String', 'Probíhá inicializace');
numFrames = video.NumberOfFrames;

%%%%%%%%%MODEL PRUMEROVANIM
frames = 100;    %pocet snimku pro vytvoreni modelu prostredi

%Ulozeni snimku do bunkoveho pole, prvni radek pro aktualni snimky, druhy
%radek pro docasne snimky, urcene pro upravu
for k = 1:frames;
    cellFrames{1, k} = read(video, k);      %ulozi k-ty snimek do privniho radku bunkoveho pole
    cellFrames{2, k} = rgb2gray(cellFrames{1, k});      %prevede snimek na sedotonovy a ulozi ho do druheho radku bun. pole
    cellFrames{2, k} = uint16(cellFrames{2, k});        
end;

[x y] = size(cellFrames{2, 1});        %velikost bunky mydata
temp = uint16(cellFrames{2, 1});      

for x = 1:frames-1              %zprumerovani snimku
  temp = cellFrames{2, x} + cellFrames{2, x+1};
  cellFrames{2, x+1}=temp;
end

temp = cellFrames{2, frames}/frames;
background = uint8(temp);

%%%%%%%%%VYBER METODY DETEKCE%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%INICIALIZACE DETEKTORU
for i = 1 : val
    prevDet{i} = false;    
end

for i = 1 : val
    prevDet2{i} = false;    
end

set(handles.detector, 'String', num2str(0));    %vynulováni citace
set(handles.text7, 'String', 'Probíhá detekce');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%METODA ROZDILU SNIMKU
if get(handles.rozdilsnimku,'Value') == 1
    for k = 1:2:numFrames-2
        x = ['Snímek ' num2str(k) '/' num2str(numFrames)];
        set(handles.text7, 'String', x);
        %preruseni cyklu v pripade stlaceni tlacitka stop
        if stop == true
            stop = false;
            break;
        end
        
        actFrame = read(video, k);
        nextFrame = read(video, k+2);
        
        detFrame = rgb2gray(nextFrame) - rgb2gray(actFrame);     %rozdil aktualniho snimku a pozadi
        detFrame = im2bw(detFrame, 0.1);    %prevod na binarni snimek
        
        
        %%%%%%%%%OZNACENI VOZIDEL%%%%%%%%%
        se = strel('square', morf);        %Nastaveni dilatace

        dilI = imdilate(detFrame, se);      %Dilatace snimku

        nobord = imclearborder(dilI, 4);    %odstraneni objektu u hranic snimku

        BW2 = bwareaopen(nobord, object, 8);   %odstraneni malych objektu
        
        if get(handles.mask, 'Value') == 1
            %%%%%%%%%MASKA POPREDI%%%%%%%%%
            mask = imread(obrazek);
            mask = im2bw(mask);
            BW2 = imsubtract(BW2,mask);
            BW2 = im2bw(BW2);
        end

        ss = regionprops(BW2, detFrame, {'BoundingBox'});      %regiony objektu
        numObj = numel(ss);      %pocet objektu ve snimku
        
        for i=1:2
        axes(handles.DetSnimek);
        imshow(actFrame);
        hold on;

        low = double(1 : numObj);
        for k = 1 : length(low)
            rectangle('Position', ss(low(k)).BoundingBox, 'EdgeColor','y');
        end
        hold off;
        end
        %%%%%%%%%POCITANI VOZIDEL%%%%%%%%%
        for i = 1 : val
            cropI = imcrop(BW2, position{2,i});       %pro kazdy detektor vypocita prumernou hodnotu pixelu v oblasti detektoru
            average = mean2(cropI);
            
            if average > 0.1 && prevDet{i} == false
                count = str2double(get(handles.detector, 'String')) + 1;    %jestlize je prumer hodnot na detektoru vyssi nez 0.1
                                                                            %a nebyla zjistena detekce v predchozim snimku, zapocita 
                                                                            %vozidlo do databaze   
                set(handles.detector, 'String', count);
                prevDet{i} = true;
            elseif average < 0.1
                prevDet{i} = false;
            end
        end
    end    
        
    
%%%%%%%%%METODA ROZDILU AKTUALNIHO SNIMKU A POZADI    
elseif get(handles.rozdilAktaPoz,'Value') == 1   
    for k = 1:2:numFrames
        x = ['Snímek ' num2str(k) '/' num2str(numFrames)]; 
        set(handles.text7, 'String', x);
        %preruseni cyklu v pripade stlaceni tlacitka stop
        if stop == true
            stop = false;
            break;
        end
        
        actFrame = read(video, k);
        detFrame = background - rgb2gray(actFrame);     %rozdil aktualniho snimku a pozadi
        detFrame = im2bw(detFrame, 0.1);    %prevod na binarni snimek
        
        %%%%%%%%%OZNACENI VOZIDEL
        se = strel('square', morf);        %Nastaveni dilatace

        dilI = imdilate(detFrame, se);      %Dilatace snimku
        
        nobord = imclearborder(dilI, 4);    %odstraneni objektu u hranic snimku

        BW2 = bwareaopen(nobord, object, 8);   %odstraneni malych objektu
        
        if get(handles.mask, 'Value') == 1
            %%%%%%%%%MASKA POPREDI%%%%%%%%%
            mask = imread(obrazek);
            mask = im2bw(mask);
            BW2 = imsubtract(BW2,mask);
            BW2 = im2bw(BW2);
        end

        ss = regionprops(BW2, detFrame, {'BoundingBox'});      %regiony objektu
        numObj = numel(ss);      %pocet objektu ve snimku
        
        
        axes(handles.DetSnimek);
        imshow(actFrame);
        
        hold on;
        low = double(1 : numObj);
        for k = 1 : length(low)
            rectangle('Position', ss(low(k)).BoundingBox, 'EdgeColor','y');
        end
        hold off;
        
        %%%%%%%%%POCITANI VOZIDEL%%%%%%%%%
        for i = 1 : val
            cropI = imcrop(BW2, position{2,i});       %pro kazdy detektor vypocita prumernou hodnotu pixelu v oblasti detektoru
            average = mean2(cropI);
            
            if average > 0.1 && prevDet{i} == false
                count = str2double(get(handles.detector, 'String')) + 1;    %jestlize je prumer hodnot na detektoru vyssi nez 0.1
                                                                            %a nebyla zjistena detekce v predchozim snimku, zapocita 
                                                                            %vozidlo do databaze   
                set(handles.detector, 'String', count);
                prevDet{i} = true;
            elseif average < 0.1
                prevDet{i} = false;
            end
        end
    end
 
%%%%%%%%%METODA DETEKCE HRANOVYM DETEKTOREM
elseif get(handles.detekcedetektorem, 'Value') == 1
    for k = 1:2:numFrames
        x = ['Snímek ' num2str(k) '/' num2str(numFrames)];
        set(handles.text7, 'String', x);
        %preruseni cyklu v pripade stlaceni tlacitka stop
        if stop == true
            stop = false;
            break;
        end
        
        actFrame = read(video, k);
        
        %vyhlazeni snimku od sumu gaussovym a medianovym filtrem
        h = fspecial('gaussian', 7, 1.0);
        FG = imfilter(actFrame, h);
        BG = imfilter(background, h);

        FG = rgb2gray(FG);

        FG = medfilt2(FG);
        BG = medfilt2(BG);
        
        edgeBG = edge(BG,'sobel',0.02);

        edgeFG = edge(FG,'sobel',0.02);

        edgeFrame = edgeBG - edgeFG;
        edgeFrame = bwareaopen(edgeFrame, object, 8);    %odstraneni malych objektu
        
        %%%%%%%%%OZNACENI VOZIDEL%%%%%%%%%
        se = strel('square', morf);        %Nastaveni dilatace    

        BW2 = imdilate(edgeFrame, se);
        BW2 = imdilate(BW2, se);
        
        se = strel('square', morf);
        BW2 = imerode(BW2, se);
        
        nobord = imclearborder(BW2, 4);    %odstraneni objektu u hranic snimku
        BW2 = bwareaopen(nobord, object, 8);    %odstraneni malych objektu
        
        if get(handles.mask, 'Value') == 1
            %%%%%%%%%MASKA POPREDI%%%%%%%%%
            mask = imread(obrazek);
            mask = im2bw(mask);
            BW2 = imsubtract(BW2,mask);
            BW2 = im2bw(BW2);
        end

        ss = regionprops(BW2, {'BoundingBox'});      %regiony objektu
        numObj = numel(ss);      %pocet objektu ve snimku
        
        axes(handles.DetSnimek);
        imshow(actFrame);
        hold on;

        low = double(1 : numObj);
        for k = 1 : length(low)
            rectangle('Position', ss(low(k)).BoundingBox, 'EdgeColor','y');
        end
        hold off;
        
        %%%%%%%%%POCITANI VOZIDEL%%%%%%%%%
        for i = 1 : val
            cropI = imcrop(BW2, position{2,i});       %pro kazdy detektor vypocita prumernou hodnotu pixelu v oblasti detektoru
            average = mean2(cropI);
            
            if average > 0.01 && prevDet{i} == false
                count = str2double(get(handles.detector, 'String')) + 1;    %jestlize je prumer hodnot na detektoru vyssi nez 0.1
                                                                            %a nebyla zjistena detekce v predchozim snimku, zapocita 
                                                                            %vozidlo do databaze   
                set(handles.detector, 'String', count);
                prevDet{i} = true;
            elseif average < 0.01
                prevDet{i} = false;
            end
        end
    end
    
%%%%%%%%%METODA VIRTUALNI SMYCKY   
else 
    for k = 1:numFrames
        x = ['Snímek ' num2str(k) '/' num2str(numFrames)];
        set(handles.text7, 'String', x);
            %preruseni cyklu v pripade stlaceni tlacitka stop
            if stop == true
                stop = false;
                break;
            end
        
            actFrame = read(video, k);
            detFrame = background - rgb2gray(actFrame);     %rozdil aktualniho snimku a pozadi
            detFrame = im2bw(detFrame, 0.1);    %prevod na binarni snimek

            detFrame = bwareaopen(detFrame, object, 8);   %odstraneni malych objektu
            
            %%%%%%%%%OZNACENI VOZIDEL
            se = strel('square', morf);        %Nastaveni dilatace       

            dilI = imdilate(detFrame,se);      %Dilatace snimku

            BW2 = bwareaopen(dilI, object, 8);   %odstraneni malych objektu
            
            if get(handles.mask, 'Value') == 1
                %%%%%%%%%MASKA POPREDI%%%%%%%%%
                mask = imread(obrazek);
                mask = im2bw(mask);
                BW2 = imsubtract(BW2,mask);
                BW2 = im2bw(BW2);
            end

            ss = regionprops(BW2, detFrame, {'BoundingBox'});      %regiony objektu
            numObj = numel(ss);      %pocet objektu ve snimku


            axes(handles.DetSnimek);
            imshow(actFrame);

            hold on;
            low = double(1 : numObj);
            for k = 1 : length(low)
                rectangle('Position', ss(low(k)).BoundingBox, 'EdgeColor','y');
            end
            hold off;

            %%%%%%%%%POCITANI VOZIDEL%%%%%%%%%
            for i = 1 : 2: val
                %VSTUPNI DETEKCE - REGISTRACNI LINIE
                cropI = imcrop(BW2, position{2,i+1});       %pro kazdy detektor vypocita prumernou hodnotu pixelu v oblasti detektoru
                average = mean2(cropI);

                if average > 0.1 && prevDet{i} == false
                    prevDet{i} = true;
                elseif average < 0.1
                    prevDet{i} = false;
                end
                
                
                
                %VYSTUPNI DETEKCE - DETEKCNI LINIE
                if prevDet{i} == false
                    cropI = imcrop(BW2, position{2,i});       %pro kazdy detektor vypocita prumernou hodnotu pixelu v oblasti detektoru
                    average = mean2(cropI);

                    if average > 0.1 && prevDet2{i} == false
                        count = str2double(get(handles.detector, 'String')) + 1;    %jestlize je prumer hodnot na detektoru vyssi nez 0.1
                                                                                    %a nebyla zjistena detekce v predchozim snimku, zapocita 
                                                                                    %vozidlo do databaze   
                        set(handles.detector, 'String', count);
                        prevDet2{i} = true;
                    elseif average < 0.1
                        prevDet2{i} = false;
                    end
                    
                    
                end
                
                
            end   
    end
end

%Vystupni zprava
set(handles.text7, 'String', 'Konec videosekvence');
end


% --- Executes during object creation, after setting all properties.
function NumFrames_CreateFcn(hObject, eventdata, handles)
% hObject    handle to NumFrames (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


% --- Executes during object creation, after setting all properties.
function numCounter_CreateFcn(hObject, eventdata, handles)
% hObject    handle to numCounter (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

% --- Executes during object creation, after setting all properties.
function numLines_CreateFcn(hObject, eventdata, handles)
% hObject    handle to numLines (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 on slider movement.
function linesSlider_Callback(hObject, eventdata, handles)
% hObject    handle to linesSlider (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,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider

sliderValue = get(handles.linesSlider,'Value');
set(handles.numLines,'String', num2str(sliderValue));
guidata(hObject, handles);


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

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end


% --- Executes during object creation, after setting all properties.
function edit2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to numLines (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 linesList_CreateFcn(hObject, eventdata, handles)
% hObject    handle to linesList (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: listbox 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 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 stop;

stop=true;

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

% Hint: listbox 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 on button press in eraseLoop.
function eraseLoop_Callback(hObject, eventdata, handles)
% hObject    handle to eraseLoop (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

global position;
global val;
global video;

selected = get(handles.linesListLoop,'Value');      %vybrana hodnota v listboxu
prev_str = get(handles.linesListLoop, 'String');

if ~isempty(prev_str)
    prev_str(get(handles.linesListLoop,'Value')) = [];
    set(handles.linesListLoop, 'String', prev_str, 'Value', min(selected,length(prev_str)));
    
    
    
    position{1,selected} = [0 0; 0 0];
    position{2,selected} = [0 0; 0 0];
    
    actFrame = read(video, 1);
    
    axes(handles.DetSnimek);
    imshow(actFrame);
    
    
    val = get(handles.linesListLoop, 'UserData') - 1;       %citac poctu prvku v listboxu minus jeden odstraneny prvek
    set(handles.linesListLoop, 'UserData', val);            %nastaveni poctu prvku v LB na aktualni hodnotu
    
    
    
    %presunuti dat na pozice smazanych
    for i = selected:val
        position{1,i} = position{1,i+1};
        position{2,i} = position{2,i+1};
    end
    
    
    for k = 1:val
        pos = position{1,k};
        a=pos(1,1);
        b=pos(1,2);
        c=pos(2,1);
        d=pos(2,2);   
        
        xx = abs(c - a);
        yy = abs(d - b);
        width = sqrt(xx^2 + yy^2);
        
        rectangle('Position', [a,b-5,width,5], 'FaceColor', 'g');   %vykresli detektory do prvniho snimku        
    end
    set(handles.linesListLoop, 'UserData', val+1);
end 

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

global cellFrames;
global position;
global val;
global loop;
global counter;

if strcmp( get(handles.detLineLoop, 'String'), 'Přidat detektor') == 1      %jestlize je tlacitko v modu 'nastavit'        
    set(handles.detLineLoop, 'String', 'Aplikovat');            

    actFrame = cellFrames{1,1};     %nacte prvni snimek

    axes(handles.DetSnimek);
    imshow(actFrame);
    
    h = imline;                 %interaktivni nastaveni pocitadla 
    pos = getPosition(h);
    
    x = get(handles.detLineLoop, 'UserData');
    position{1,x} = pos;
    set(handles.detLineLoop, 'UserData', x+1);
    
%jestlize je tlacitko v modu 'aplikovat' nebo 'Přidat registrační linii'     
elseif strcmp( get(handles.detLineLoop, 'String'), 'Aplikovat') == 1      
    
    set(handles.detLineLoop, 'String', 'Přidat detektor');
    
    actFrame = cellFrames{1,1};
    
    axes(handles.DetSnimek);
    imshow(actFrame);
            
    val = get(handles.linesListLoop, 'UserData') + 1;       %citac poctu prvku v listboxu
    
    for k = 1:val
        pos = position{1,k};
        
        a=pos(1,1);
        b=pos(1,2);
        c=pos(2,1);
        d=pos(2,2);   
        
        xx = abs(c - a);
        yy = abs(d - b);
        width = sqrt(xx^2 + yy^2);
        
        rectangle('Position', [a,b-5,width,5], 'FaceColor', 'g');   %vykresli detektory do prvniho snimku

        position{2,k} = [a,b-5,width,5];        %zapise souradnice detektoru do bunky
    end

    set(handles.linesListLoop, 'UserData', val);

    data = get(handles.linesListLoop, 'String');        %precte listbox
    
    if loop == false
        namee = ['detekcni linie ' num2str(val)];      %nazev detektoru
    else                                                %loop == true
        namee = ['registracni linie ' num2str(val)];      %nazev detektoru
    end
    
    data{val} = namee;
    set(handles.linesListLoop, 'String', data);     %ulozi nazvy detektoru do listboxu
    
    if get(handles.virtualnismycka, 'Value') == 1 && loop == false
        loop = true;
    else
        loop = false;
    end
    
    counter = true;
    
end

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

global obrazek;

obrazek = uigetfile( ...
{'*.jpg;*.jpeg;*.jpe;','JPEG (*.jpg,*.jpeg,*.jpe)';    %typy k otevreni; zobrazeni v openboxu
   '*.gif',  'GIF (*.GIF)'; ...
   '*.png','PNG (*.PNG)'; ...
   '*.bmp','bitmapy (*.bmp)'}, ... %'*.*',  'All Files (*.*)'}, ...      
   'Otevřít obrázek');                  %Popis open boxu

set(handles.text7, 'String', 'Maska načtena');


% --- Executes during object creation, after setting all properties.
function objekty_CreateFcn(hObject, eventdata, handles)
% hObject    handle to objekty (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 strel_CreateFcn(hObject, eventdata, handles)
% hObject    handle to strel (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
