%
% Mammogram.m
%
%  This is homework 3, problem 1, ECE 5273, Spring 2011.
%
%  jph 21 April 2002
%  jph 21 February 2011: this is now HW 3.
%  jph 04 February 2014: removed loop for threshold to make it run faster.
%  jph 08 February 2015: changed the figure titles
%
%

xsize = 256;

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

%
% Threshold at the empirically determined value thresh=108
%
thresh = 108;
x = 255 * (xorig >= thresh);

%
% Display and print thresholding result
%
figure(2);colormap(gray(256));
image(x);axis('image');
title('Thresholding Result: \tau=95','FontSize',12);
print -deps Mresult1Crop.eps;
print -dpdf Mresult1.pdf;

%
% Make output image y using the algorithm on page 2.105 of the notes
%
y = zeros(xsize,xsize);
for row=1:xsize
  for col=1:xsize
    if (x(row,col) == 255)
      y(row,col) = 0;
    else
      if (  ((col > 1) & (x(row,col-1)==255))...    % left  neighbor logic ONE
          | ((col < xsize) & (x(row,col+1)==255))... % right neighbor logic ONE
          | ((row > 1) & (x(row-1,col)==255))...    % upper neighbor logic ONE
          | ((row < xsize) & (x(row+1,col)==255))... % lower neighbor logic ONE
         )
        y(row,col) = 255;
      else
        y(row,col) = 0;
      end
    end
  end
end

%
% Display and print result
%
figure(3);colormap(gray(256));
image(y);axis('image');
title('Approximate Contour Generation Result','FontSize',12);
print -deps Mresult2Crop.eps;
print -dpdf Mresult2.pdf;
