function C = postalseg(image)
%POSTALSEG Block-segmentation and classification of postal images.
%   C = POSTALSEG(IMAGE) block-segments and classifies the postal image IMAGE
%   into the categories: picture, text, and background.  The matrix C holds 
%   the classification of each pixel of IMAGE.  The values of C are as follows: 
%
%   1 = picture
%   2 = text
%   3 = background
%   4 = undetermined
%
%   IMAGE specifies the filename of a grayscale image in a format supported by
%   IMREAD.  IMAGE must have dimensions that are integer multiples of 64x64.  
%
%   See also IMREAD

%   Author(s): K. R. Varshney
%   School of Electrical and Computer Engineering, Cornell University
%   $Date: 2002/08/15 $

tic
blocksize = 32;

% get pixel value matrix
I = imread(image);

% perform first pass classification
CI = firstpass(I);

% perform context-based classification
while (blocksize >= 16)
    CI = splitCI(CI);

    [L, m, CIpui] = step12(CI, blocksize, I);
    
    CI = L_classifier(m, L, CIpui, I, blocksize);
    
    blocksize = blocksize/2;  
end

% create output matrix that has one-to-one correspondence with input image
C = uint8(CI(:,:,2));
C = splitCI(C);
C = splitCI(C);
C = splitCI(C);
C = splitCI(C);

toc

% display results
figure(1);
colormap(gray);
imagesc(I);
[sr,sc] = size(I);
hold on;
for i=1:sc/64-1
    plot([i*64 i*64], [2 sr-2]);
end
for i=1:sr/64-1
	plot([2 sc-2], [i*64 i*64]);
end
hold off;
axis image;  
axis off;

figure(2)
imagesc(C);
hold on;
for i=1:sc/64-1
    plot([i*64 i*64], [2 sr-2]);
end
for i=1:sr/64-1
	plot([2 sc-2], [i*64 i*64]);
end
hold off;
axis image;
axis off;
