%
% FindT.m
%
%  This is homework 3, problem 3, ECE 5273, Spring 2015.
%
%  jph 21 April 2002
%  jph 21 February 2011: this is now HW 3.
%  jph 04 February 2014: remove some loops to speed it up.
%  jph 08 February 2015: compute threshold automatically,
%                        threshold J2 directly instead of y
%

xsize = 256;

%
% read actontBin.bin, transpose, display, and print
%
x = ReadBin('actontBin.bin',xsize);
figure(1);colormap(gray(256));
image(x);axis('image');
title('Original actontBin Image','FontSize',12);
print -deps MactontBinCrop.eps;
print -dpdf MactontBin.pdf;

%
% Construct template based on analysis of the image
%
TemplRows = 47;
TemplRowso2 = floor(TemplRows/2);
TemplCols = 15;
TemplColso2 = floor(TemplCols/2);

Templ = zeros(TemplRows,TemplCols);

for row=1:10
  for col=1:TemplCols
    Templ(row,col) = 0;
  end
end
for row=11:16
  for col=1:TemplCols
    Templ(row,col) = 255;
  end
end
for row=17:37
  for col=1:6
    Templ(row,col) = 0;
  end
  for col=7:10
    Templ(row,col) = 255;
  end
  for col=11:TemplCols
    Templ(row,col) = 0;
  end
end
for row=38:TemplRows
  for col=1:TemplCols
    Templ(row,col) = 0;
  end
end

%
% Initialize output image J1
%
J1 = zeros(xsize,xsize);

%
% Loop over image pixels computing the match measure M2
%
for row=TemplRowso2+1:xsize-TemplRowso2
  for col=TemplColso2+1:xsize-TemplColso2
    WindowSet = ...
           x(row-TemplRowso2:row+TemplRowso2,col-TemplColso2:col+TemplColso2);
    J1(row,col) = sum(sum(WindowSet == Templ));
  end
end

%
% Perform full-scale stretch.  Display and write J1.
%
y = stretch(J1);
figure(2);colormap(gray(256));
image(y);axis('image');
title('J1 = M_2(i,j)','FontSize',12);
print -deps MJ1Crop.eps;
print -dpdf MJ1.pdf;

%
% Create J2
%
% The two highest counts M2(i,j) in J1 should correspond to the centers of
% the two T's.  Use this fact to compute the threshold.
%
counts = sort(J1(:),'descend');
thresh = counts(2);
J2 = 255 * (J1 >= thresh);

%
% display and write J2
%
figure(3);colormap(gray(256));
image(J2);axis('image');
title(sprintf('J2; \\tau=%d',thresh),'FontSize',12);
print -deps MJ2Crop.eps;
print -dpdf MJ2.pdf;
