clear
close all

image_data = imread('night.png');
image_data= imresize(image_data,1/2);
image_data = double(0.2126*image_data(:,:,1)+0.7152*image_data(:,:,2)+0.0722*image_data(:,:,3));
[N,M ] = size(image_data);

im = image_data(:);
im_norm =  im - sum(im)/length(im);
xcorr( im_norm , im_norm ,'coeff'  );
autocov  = xcorr( im_norm, im_norm, 'coeff'  );

Na = length(im);
Cx = zeros( Na, Na );
for n = 1 : Na-1
    Cx( n, : ) = autocov( floor(length(autocov)/2) + 2 - n  : floor(length(autocov)/2) + Na - n +1 ) ;
end
%%
[U,V] = eig(Cx);
%%
n = 16;
v1 = reshape(U(:,n),N,M);
%
pcolor(flipud(v1));shading interp
%%
out_1 = U'*im_norm;
N0 = 5500;
out = zeros(N,M);

f = figure('units','normalized','outerposition',[0 0 1 1])
% 
% subplot(1,3,1)
% pcolor(flipud(image_data));shading interp
% axis equal tight

subplot(1,2,1)
p2 = pcolor(flipud(out));shading interp
axis equal tight
linkdata on

subplot(1,2,2)
p3 = pcolor(flipud(image_data-out));shading interp
axis equal tight

colormap(gray)
v = diag(V);
for i = 1 : N0
    v_act = reshape(U(:,i),N,M);
    out = out + out_1(i)*v_act;
    set(p2, 'CData', flipud(out));
    set(p3, 'CData', flipud(out_1(i)*v_act));
    drawnow
    pause(0.001)
end

