% seg.m - Image Segmentation by
% 1. Gonzalez,  2. Otsu  [low, high, T1, T2-1]
fin=fopen('linsfN.raw','r');
m=640; n=896;
I=fread(fin,n*m,'uint8=>unit8');  fclose(fin); A=reshape(I,n,m); A=A';
% 1. Gonzalez
T1=(min(min(A))+max(max(A)))/2;
done=false;
delta=0.5;    % a small number
while ~done
    g=(A>=T1);
    tx=(mean(A(g))+mean(A(~g)))/2;
    done=abs(T1-tx) < delta;
    T1=tx;
end
for i=1:m  
  for j=1:n if (A(i,j)<T1) B1(i,j)=30; else B1(i,j)=180; end; end
end
% 2. Otsu ~ graythresh(A)
T2=otsu(A,m,n); % T1, T2
for i=1:m  
  for j=1:n if (A(i,j)<=T2) B2(i,j)=30; else B2(i,j)=180; end; end
end
subplot(2,2,1)
imshow(double(A)/255)
M=256;  % 256 bins 
subplot(2,2,2)
hist(I,M)
title('Histogram of Image Scene')
subplot(2,2,3)
imshow(double(B1)/255)
title('Gonzalez Segmentation with T=131')
subplot(2,2,4)
imshow(double(B2)/255)
title('Otsu Segmentation with T=131')
