close all; clear all; clc; profile on; 
global file_name
file_name='..\img\vlcsnap-2010-10-10-21h09m35s62.png';

x=(imread(file_name));

x=x(1:end-50,:,:);
img=double(rgb2gray(x));
x_x=double(imfilter(img,fspecial('sobel')));
x_y=double(imfilter(img,fspecial('sobel')'));
x_c=sqrt(x_x.^2+x_y.^2);
x_angle=atan2(x_y,x_x);
im_edge=double(edge(img,'canny'));

im_angle = x_angle.*double(im_edge);

[m n]=size(im_edge);
disp('oznacte horizont')
 figure(3),imshow(im_edge,[]),colormap('default'),[hzy hz]=ginput(1)
 global g_im
 g_im=im_edge;
pause(0.1)


%% simulované žíhání
tic
lb = [-10000 -500 -10000 -200]; %dolni meze parametrů
ub = [10000 500 10000 200];     %horni meze parametrů

options = saoptimset('PlotFcns',{@saplotbestf,@saplottemperature,@saplotf,@plotfunc},'InitialTemperature',100,'TemperatureFcn',@temperaturegeom,'ReannealInterval',100);
ObjectiveFunction =  @(x) simple_objective(x,im_edge,im_angle,hz);
X0 = [0 1 n/2 1];   %počáteční parametry
[s,fval,exitFlag,output] = simulannealbnd(ObjectiveFunction,X0,lb,ub,options)

toc
%% vykreslení výsledků
xx=hz:m;
ER = s(1)./ (xx - hz) + s(2) .* (xx - hz) + s(3);
EL = s(1)./ (xx - hz) + s(4) .* (xx - hz) + s(3);
ER2 = s(2) .* (xx - hz) + s(3);
EL2 = s(4) .* (xx - hz) + s(3);

figure(4545454),imshow(im_edge,[]),hold on
plot(ER,xx,'r','LineWidth',2)
plot(EL,xx,'g','LineWidth',2)


hold off

figure(4545455),imshow(x,[]),hold on
plot(ER,xx,'r','LineWidth',2)
plot(EL,xx,'g','LineWidth',2)

%% řeseni pomoci genetickych alkoritmu
% tic
% 
% options = gaoptimset('PopulationSize',100,'Generations', 1000);
% FitnessFunction = @(x) simple_objective(x,im_edge,im_angle,hz);
% numberOfVariables = 4;
% [s fval exitflag output population scores] = ga(FitnessFunction,numberOfVariables,[],[],[],[],[],[],[],options)
% 
% toc
% 
% xx=hz:n;
% ER = s(1)./ (xx - hz) + s(2) .* (xx - hz) + s(3);
% EL = s(1)./ (xx - hz) + s(4) .* (xx - hz) + s(3);
% figure(45454542),imshow(im_edge,[]),hold on
% plot(ER,xx,'r')
% plot(EL,xx,'g')
% hold off

% s=fminsearch(@(x) simple_objective(x,im_edge,im_angle,hz),X0)
%  xx=hz:n;
% ER = s(1)./ (xx - hz) + s(2) .* (xx - hz) + s(3);
% EL = s(1)./ (xx - hz) + s(4) .* (xx - hz) + s(3);
% figure(45454542),imshow(im_edge,[]),hold on
% plot(ER,xx,'r')
% plot(EL,xx,'g')
% hold off

