%Longin Jan Latecki, latecki@temple.edu, July 2004
%incremental PCA algorithm that calles Pokie's incremental_PCA3_step for every image block
%We incrementally learn the EigenVectors and Values, then project, and finally reconstruct the image using the EigenVectors.
%as it is, it is not a function, but one can make it if the second line below is uncommented

%usuage: imPCA2(filename, 8, 8, 10, 0.99);

%function [] = imPCA1(filename, w, h, dim, alpha);

clear all;
close all;
tic;
w=8;
h=8;
dim=10;
alpha=0.99; 

%first we read a test image
%directory = 'E:\Temple\2004 Fall CIS 601\Code\PCA_new\';
%filename = strcat(directory,'bigpart33.jpg')
filename = 'sample4.tif';

%computation of projection matrix composed of eigenvectors in igenVectors
[x, imagerows, imagecols] = cut_evzr(filename, w, h); %we just want x, where each block is one column
[EigenVectors, Values] = pca_rep(x(:,1:100), dim, imagerows, imagecols); %We compute EigenVectors and Values only for the first 100 blocks
%EigenVectors is the projection matrix composed of eigen vectors
%Values are eigen values

% save EV32X32dim10.mat EigenVectors;


num = size(x,2);


% incremental PCA is computed here
x=x';
mu=mean(x)';
for i=1:num 
    Proj(:,i) = EigenVectors' * (x(i,:)- mean(x(i,:)))'; %we project a block using EigenVectors learned without this block
    [Values,EigenVectors,mu]=incremental_PCA3_step(x(i,:),dim,alpha,EigenVectors,Values, mu);
end   

r(1,:)=mean(Proj);
r(2,:)=std(Proj);

scatter(r(1,:),r(2,:));
axis equal;
drawnow;
pause;

%showing the original image with red letters
addcolor_temp = ones(imagerows, imagecols) .* 0;
addcolor = im2col(addcolor_temp,[h w],'distinct');
Letters=find(r(2,:)>0.25);
addcolor(:,Letters) = 1;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
image = imread(filename);
YIQ = rgb2ntsc(image);
YIQ=double(image)./255; 
Original=YIQ(:,:,1);
Original=Original(1:imagerows,1:imagecols);

AL(:,:,1) = Original;
AL(:,:,2) = Original;
AL(:,:,3) = col2im(addcolor,[h w],[imagerows imagecols],'distinct');;

figure; imshow(AL);

t=toc